Python Modules



What are modules in Python?

In Python, a module refers to a file containing statements and definitions.

A module can define variables, functions, classes. It can also contain runnable code.

We use modules to break down large programs into small manageable by grouping related code into modules that make the code logically organized and easier to understand and use.

A module is a file containing Python code, for example: demo.py, is called a module, and its module name would be demo.

We can define the most used functions into a module, so we can import the module into different programs instead of copying functions definitions.

Let us create a module. We will create a module named demo, and save it as demo.py.

# Python module 

def my_func():
    """ This program print hello world """

    print("Hello World")

As we can see above, we defined a function my_func() inside a module named demo. The defined function print "Hello World".


How to import modules?

The definitions inside a module can be imported to another module or the Python interpreter.

To import modules, we use the import keyword.

In the following example, we will import the previously defined module demo in the Python prompt.

>>> import demo

The above sentence does not import the functions defined in the demo module in the current symbol table. It only imports the module name demo.

Using the module name, we can access the demo functions using the dot . operator.

>>> demo.print()
Hello World

Python has multiples of standard modules. You can check out the complete list of Python standard modules and their use cases.

Standard modules can be imported the same way as we imported the demo module.


Python import statement

The import keyword can be used to import a module. To access the definitions inside the imported module, we use the dot . operator.

In the following example, we will import the math module and print the pi value.

# Import standard module math

import math

print("The value of pi is", math.pi)

Output

The value of pi is 3.141592653589793

Import with renaming

When importing a module, we can rename it as follows:

# import module by renaming it

import math as m

print("The value of pi is", m.pi)

Output

The value of pi is 3.141592653589793

As we can see above, we have renamed the math module as m.

Note: After renaming the math module when importing, it will not be recognized in the scope. Hence, math.pi is invalid, and m.pi is the correct implementation.


Python from...import statement

Using Python's from...import statement, we can import specific attributes from a module into the current namespace.

The from...import has the following statement.

from module_name import name_1[, name_2[, ... name_N]]

For example, to import the pi attribute from the math module, we will use the following statement.

# import only pi from math module

from math import pi

print("The value of pi is", pi)

Output

The value of pi is 3.141592653589793

When using the from...import statement, we don't need to use the dot operator, and we can import multiple attributes as follows:

from math import pi, e

print("The value of pi is", pi)
print("The value of e is", e)

Output

The value of pi is 3.141592653589793 
The value of e is 2.718281828459045

Import all names

We can import all names (definitions) from a module into the current namespace using the asterisk * .

# import all names from the standard module math

from math import *

print("The value of pi is", pi)
print("The value of e is", e)

Output

The value of pi is 3.141592653589793
The value of e is 2.718281828459045

In the above code, we have imported all the definitions from the standard math module. This includes all names visible in our scope, excluding those beginning with an underscore _ (private definitions).

Note: Importing all the definitions with the asterisk * symbol is not a good programming practice. It can lead to duplicate definitions for an identifier and affect the readability of the code.


Built-in Modules

Python provides several built-in modules that can be imported whenever you like.

In the following example, we will import the platform module.

import platform 

print(platform.system())

Output

Linux

Python Module Search Path

While importing a module, Python verifies several places. Python interpreter first looks for a built-in module. Then (if it is not founded in the built-in module), Python looks into a list of directories defined in sys.path. The search can be in this order.

  • The current directory.
  • PYTHONPATH (an environment variable with a list of directories).
  • The installation-dependent default directory.
>>> import sys
>>> sys.path
['',
 '/content',
 '/env/python',
 '/usr/lib/python37.zip',
 '/usr/lib/python3.7',
 '/usr/lib/python3.7/lib-dynload',
 '/usr/local/lib/python3.7/dist-packages',
 '/usr/lib/python3/dist-packages',
 '/usr/local/lib/python3.7/dist-packages/IPython/extensions',
 '/root/.ipython']

We can add and modify this list to add our path.


Reloading a module

The Python interpreter imports modules only once during a session.

Let us consider that we have the following code in a module named demo_module.

print("The code from the demo_module")

Now, we will see the effect of multiple imports.

>>> import demo_module
The code from the demo_module
>>> import demo_module
>>> import demo_module

As we can see above, the code inside the demo_module got executed once, even if we imported it multiple times. This means that our module was imported only once.

If our module changed during the execution of the program, we need to reload it. We can reload the module by restarting the interpreter, but it is not a nice way to do it.

Python offers the reload() function from the imp module to reload a module.

>>> import imp
>>> import demo_module
The code from the demo_module
>>> import demo_module
>>> imp.reload(demo_module)
The code from the demo_module
<module 'demo_module' from '.\\demo_module.py'>

The dir() built-in function

The dir() function is used to find out names that are defined inside a specific module.

For example, we have defined the function my_func() in the module demo that we had created initially.

Let us use the dir() function in the demo module in the following way.

>>> import demo
>>> dir(demo)
 ['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'my_func']

As we can see above, a sorted list of names (along with my_func) is printed. All the names starting with an underscore are default Python attributes associated with the module (not user-defined).

For example, the __name__ attribute includes the name of the module.

>>> import demo
>>> demo.__name__
'demo'

All the names defined in the current namespace can be found using the dir() function without any arguments.

>>> x = 6
>>> y = "Hello World"
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'x', 'y', 'math', 'pyscripter']


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.