How to Import Modules in Python

09/07/2021

Contents

In this article, you will learn how to import modules in Python.

Import modules in Python

To import a module in Python, you use the import statement. For example, to import the math module, you would write:

import math

Once the module is imported, you can use its functions and attributes by prefixing the module name to the function or attribute name. For example, to use the sqrt function from the math module, you would write:

math.sqrt(4)

You can also import specific functions from a module using the from keyword. For example:

from math import sqrt

After importing sqrt in this way, you can use it directly, without prefixing the module name:

sqrt(4)

Import multiple modules

The import statement can be used to import multiple modules in one line, separated by commas. For example:

import math, sys, os

Give an alias to a module

You can give an alias to a module using the as keyword. For example:

import math as m

Now you can use the math module with the alias m:

m.sqrt(4)

Use the dir() function

You can use the dir function to see what functions and attributes are available in a module. For example:

import math
print(dir(math))

Use the help() function

You can use the help function to see the documentation for a module or function. For example:

import math
help(math)

Import all functions and attributes from a module

You can use * (wildcard) to import all functions and attributes from a module. This is not recommended as it can lead to naming collisions and make your code harder to read. For example:

from math import *

Python has a large number of built-in modules that you can use, and you can also install third-party modules using a package manager such as pip.