Python Language Importing modules Importing a module

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Use the import statement:

>>> import random
>>> print(random.randint(1, 10))
4

import module will import a module and then allow you to reference its objects -- values, functions and classes, for example -- using the module.name syntax. In the above example, the random module is imported, which contains the randint function. So by importing random you can call randint with random.randint.

You can import a module and assign it to a different name:

>>> import random as rn
>>> print(rn.randint(1, 10))
4

If your python file main.py is in the same folder as custom.py. You can import it like this:

import custom

It is also possible to import a function from a module:

>>> from math import sin
>>> sin(1)
0.8414709848078965

To import specific functions deeper down into a module, the dot operator may be used only on the left side of the import keyword:

from urllib.request import urlopen

In python, we have two ways to call function from top level. One is import and another is from. We should use import when we have a possibility of name collision. Suppose we have hello.py file and world.py files having same function named function. Then import statement will work good.

from hello import function
from world import function

function() #world's function will be invoked. Not hello's  

In general import will provide you a namespace.

import hello
import world

hello.function() # exclusively hello's function will be invoked 
world.function() # exclusively world's function will be invoked

But if you are sure enough, in your whole project there is no way having same function name you should use from statement

Multiple imports can be made on the same line:

>>> # Multiple modules
>>> import time, sockets, random
>>> # Multiple functions
>>> from math import sin, cos, tan
>>> # Multiple constants
>>> from math import pi, e

>>> print(pi)
3.141592653589793
>>> print(cos(45))
0.5253219888177297
>>> print(time.time())
1482807222.7240417

The keywords and syntax shown above can also be used in combinations:

>>> from urllib.request import urlopen as geturl, pathname2url as path2url, getproxies
>>> from math import factorial as fact, gamma, atan as arctan
>>> import random.randint, time, sys

>>> print(time.time())
1482807222.7240417
>>> print(arctan(60))
1.554131203080956
>>> filepath = "/dogs/jumping poodle (december).png"
>>> print(path2url(filepath))
/dogs/jumping%20poodle%20%28december%29.png


Got any Python Language Question?