Importing a module

suggest change

Use the import statement:

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

4 is one possible result. 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

Python has two ways to use a name from another module: import and from. Use import when the same name might come from more than one module. Suppose hello.py and world.py both define function. A from import binds that name directly, so the second import replaces the first:

from hello import function
from world import function

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

An import keeps each module in its own namespace:

import hello
import world

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

If the project has no colliding names, a from import is fine.

Multiple imports can be made on the same line:

>>> # Multiple modules
>>> import time, socket, 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())  # illustrative timestamp
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 time, sys

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents