Importing a module

Download python eBook


Use the import statement:

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

import module will import a module and then allow you to reference its objects -- values, functions and classes, for example -- using the 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))

If your python file is in the same folder as 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)

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 file and 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)
>>> print(cos(45))
>>> print(time.time())

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())
>>> print(arctan(60))
>>> filepath = "/dogs/jumping poodle (december).png"
>>> print(path2url(filepath))


Contributors: 12
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook