How does the import module work in Python π
import
statement works and different forms of importing.
In Python, Whenever you want to import a module, you write as following -
import module_name
1. How import works?
2. What happens if a module is imported twice?
3. Different forms of the import statement
When you call 2. What happens if a module is imported twice?
3. Different forms of the import statement
import
in Python, the interpreter searches the module through a set of directories for the name provided and runs all the code in the module file. The list of directories that it searches is stored in sys.path
and can be modified during run-time.
Pythonβs documentation about sys.path
is as follows -
A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH
, plus an installation-dependent default.
Now letβs move to the practical, I have created a module file dev.py
and written a few lines of code.
touch dev.py
language = 'Python'
framework = 'Django'
def hello_world():
print('Hey !!! welcome back')
class ModuleTest:
def get_language(self):
print('My favroite language is - {}'.format(language))
>>> import dev
>>> dev.language
'Python'
>>> dev.framework
'Django'
>>> dev.hello_world()
Hey !!! welcome back
>>> obj = ModuleTest()
>>> obj.get_language()
My favroite language is - Python
How import works?
As I told earlier when the interpreter executes theimport dev
statement, it searches sequentially in specific locations until it finds it -
1. It looks in the current directory where the input script was run.
2. PYTHONPATH - If PYTHONPATH
is set, then Python will include the directories in sys.path
for searching. You can set the: PYTHONPATH
as follows,
export PYTHONPATH='/some/extra/path'
python -c "import sys; print(sys.path)"
o/p - ['', '/usr/lib/python36.zip',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/prashant/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
sys.path
at run-time so that it contains that directory.
For example, I can put my module dev.py
in directory /home/prashant/Desktop
and then update as following and Python should be able to find the module without any issue.
>>> sys.path.append('/home/prashant/Desktop')
>>> sys.path
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/prashant/.local/lib/python3.6/site-packages',
'/usr/local/lib/python3.6/dist-packages',
'/usr/lib/python3/dist-packages', '/home/prashant/Desktop']
>>>
>>> import dev
>>> dev.language
'Python'
What happens if a module is imported twice?
The module is only loaded the first time the import statement is executed and there is no performance loss by importing it again. You can examinesys.modules
to find out which modules have already been loaded.
>>> import sys
>>> sys.modules.keys()
dict_keys(['builtins', 'sys', '_frozen_importlib', '_imp', '_warnings', '_thread', '_weakref', '_frozen_importlib_external', '_io', 'marshal', 'posix', 'zipimport', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', 'io', 'abc', '_weakrefset', 'site', 'os', 'errno', 'stat', '_stat', 'posixpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins', 'sysconfig', '_sysconfigdata_m_linux_x86_64-linux-gnu', '_bootlocale', '_locale', 'types', 'functools', '_functools', 'collections', 'operator', '_operator', 'keyword', 'heapq', '_heapq', 'itertools', 'reprlib', '_collections', 'weakref', 'collections.abc', 'importlib', 'importlib._bootstrap', 'importlib._bootstrap_external', 'warnings', 'importlib.util', 'importlib.abc', 'importlib.machinery', 'contextlib', 'backports', 'zope', 'sitecustomize', 'apport_python_hook', 'readline', 'atexit', 'rlcompleter', 'dev'])
>>> sys.modules['dev']
<module 'dev' from '/home/prashant/Desktop/dev.py'>
For Python2.x
reload(module)
For above 2.x and <=Python3.3
import imp
imp.reload(module)
For >=Python3.4
import importlib
importlib.reload(module)
Different forms of the import statement
import
We can import the module using the import statement and access the variables, methods, and classes inside it using the dot operator.
>>> import dev
>>> dev.language
'Python'
from import
We can also import the specific variable, methods, classes from the module without importing it as a whole as below-
>>> from dev import language
>>> language
'Python'
>>> language = 'java'
>>> from dev import language
>>> language
'Python'
object id
into memory
As you can differ between both using the following example,
>>> language='java'
>>> id(language)
139635543372736
>>> from dev import language
>>> id(language)
139635542592128
from import as
We can also import a specific object from a module with an alternative name, This can avoid conflict with previously existing names.
>>> language='java'
>>> from dev import language as lang
>>> lang
'Python'
import as
We can also import the entire module with an alternate name.
>>> import dev as dev2
>>> dev2.language
'Python'
from import *
We can import everything from a module.
from dev import *
About Author
Prashant Sharma
An Engineering professional with 3+ years of experience in Software development. He is a Post-graduate in CS from National Institute of Technology Calicut. He loves learning new stuff and writing about it.
Please share your Feedback:
Did you enjoy reading or think it can be improved? Donβt forget to leave your thoughts in the comments section below! If you liked this article, please share it with your friends, and read a few more!