Importing modules in Python

Importing modules in Python can be done easily. 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.

Importing modules in python: Importing a module

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

Importing modules in python: The all special variable

Modules can have a special variable named all to restrict what variables are imported when using from mymodule import *.

Given the following module:

mymodule.py

all = ['imported_by_star']
imported_by_star = 42
not_imported_by_star = 21
Only imported_by_star is imported when using from mymodule import *:
from mymodule import *
imported_by_star
42
not_imported_by_star Traceback (most recent call last):
File "", line 1, in
NameError: name 'not_imported_by_star' is not defined

However, not_imported_by_star can be imported explicitly:

from mymodule import not_imported_by_star
not_imported_by_star
21

Importing modules in python: Import modules from an arbitrary filesystem location

If you want to import a module that doesn’t already exist as a built-in module in the Python Standard Library nor as a side-package, you can do this by adding the path to the directory where your module is found to sys.path. This may be useful where multiple python environments exist on a host.

import sys
sys.path.append("/path/to/directory/containing/your/module")
import mymodule

It is important that you append the path to the directory in which mymodule is found, not the path to the module itself.

Importing modules in python: Importing all names from a module

from module_name import *

for example:

from math import *
sqrt(2) # instead of math.sqrt(2)
ceil(2.7) # instead of math.ceil(2.7)

This will import all names defined in the math module into the global namespace, other than names that begin with an underscore (which indicates that the writer feels that it is for internal use only).

Warning: If a function with the same name was already defined or imported, it will be overwritten. Almost always importing only specific names from math import sqrt, ceil is the recommended way:

def sqrt(num):
print("I don't know what's the square root of {}.".format(num))
sqrt(4)

Output: I don’t know what’s the square root of 4.

from math import *
sqrt(4)

Output: 2.0

Starred imports are only allowed at the module level. Attempts to perform them in class or function definitions result in a SyntaxError.

def f():
from math import *

and

class A:
from math import *

both fail with:

SyntaxError: import * only allowed at module level

Programmatic importing

Python 2.x Version ≥ 2.7

To import a module through a function call, use the importlib module (included in Python starting in version 2.7):

import importlib
random = importlib.import_module("random")

The importlib.import_module() function will also import the submodule of a package directly:

collections_abc = importlib.import_module("collections.abc")

For older versions of Python, use the imp module.

Python 2.x Version ≤ 2.7

Use the functions imp.find_module and imp.load_module to perform a programmatic import.

Taken from standard library documentation

import imp, sys
def import_module(name):
fp, pathname, description = imp.find_module(name)
try:
return imp.load_module(name, fp, pathname, description)
finally:
if fp:
fp.close()

Do NOT use import() to programmatically import modules! There are subtle details involving sys.modules, the fromlist argument, etc. that are easy to overlook which importlib.import_module() handles for you.

PEP8 rules for Imports

Some recommended PEP8 style guidelines for imports:

  1. Imports should be on separate lines:
    from math import sqrt, ceil # Not recommended
    from math import sqrt # Recommended
    from math import ceil
  2. Order imports as follows at the top of the module: Standard library imports Related third party imports Local application/library specific imports Wildcard imports should be avoided as it leads to confusion in names in the current namespace. If you do from module import *, it can be unclear if a specific name in your code comes from module or not. This is

doubly true if you have multiple from module import *-type statements.

  1. Avoid using relative imports; use explicit imports instead.

Importing modules in python: Importing specific names from a module

Instead of importing the complete module you can import only specified names:
from random import randint # Syntax "from MODULENAME import NAME1[, NAME2[, …]]"
print(randint(1, 10)) # Out: 5

from random is needed, because the python interpreter has to know from which resource it should import a function or class and import randint specifies the function or class itself.

Another example below (similar to the one above):

from math import pi
print(pi) # Out: 3.14159265359

The following example will raise an error, because we haven’t imported a module:

random.randrange(1, 10) # works only if "import random" has been run before

Outputs:

NameError: name 'random' is not defined

The python interpreter does not understand what you mean with random. It needs to be declared by adding import random to the example:

import random
random.randrange(1, 10)

Importing submodules

from module.submodule import function

This imports function from module.submodule.

Importing modules in python: Re-importing a module

When using the interactive interpreter, you might want to reload a module. This can be useful if you’re editing a module and want to import the newest version, or if you’ve monkey-patched an element of an existing module and want to revert your changes.

Note that you can’t just import the module again to revert:

import math
math.pi = 3
print(math.pi) # 3
import math
print(math.pi) # 3

This is because the interpreter registers every module you import. And when you try to reimport a module, the interpreter sees it in the register and does nothing. So the hard way to reimport is to use import after removing the corresponding item from the register:

print(math.pi) # 3
import sys
if 'math' in sys.modules: # Is the math module in the register?
del sys.modules['math'] # If so, remove it.
import math
print(math.pi) # 3.141592653589793
But there is more a straightforward and simple way.

Python 2

Use the reload function:

Python 2.x Version ≥ 2.3

import math
math.pi = 3
print(math.pi) # 3
reload(math)
print(math.pi) # 3.141592653589793

Python 3

The reload function has moved to importlib:

Python 3.x Version ≥ 3.0

import math
math.pi = 3
print(math.pi) # 3
from importlib import reload
reload(math)
print(math.pi) # 3.141592653589793

import() function

The import() function can be used to import modules where the name is only known at runtime

if user_input == "os":
os = import("os")

equivalent to import os

This function can also be used to specify the file path to a module

mod = import(r"C:/path/to/file/anywhere/on/computer/module.py")

Learn more

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment