Python – Modules

In this post, you’ll learn how to write and import custom Python modules. In addition, you’ll learn how to import and use custom and built-in modules in Python.

What are modules in Python?

A file containing Python commands and definitions is referred to as a module.

A module helps you to structure your Python code in a logical manner. The code is easier to comprehend and utilize when it is organized into modules. You can bind and reference a module, which is a Python object with arbitrarily named attributes.

A module is simply a file containing Python code. Functions, classes, and variables can all be defined in a module. Runnable code can also be included in a module.

Let’s start by making a module. Save the file as example.py by typing the following.

# Python Module example

def add(a, b):
   """This program adds two
   numbers and return the result"""

   result = a + b
   return result

Within the example module, we’ve defined the function add(). The function accepts two numbers as input and returns the total of them.

How to import modules in Python?

In Python, we can import the definitions from one module into another or into the interactive interpreter.

To do so, we employ the import keyword. In the Python prompt, type the following to import our previously defined module example.

>>> import example

To do so, we employ the import keyword. In the Python prompt, type the following to import our previously defined module example.

Using the dot. operator and the module name, we can get to the function. Consider the following scenario:

>>> example.add(4,5.5)
9.5

Python comes with a large number of standard modules. The complete collection of Python standard modules and their use cases may be found here. These files can be found in the Lib directory of the Python installation path.

Standard modules can be imported in the same way that user-defined modules are imported.

Importing modules can be done in a variety of ways. The following is a list of them.

Python import statement

We can use the import statement to import a module and the dot operator to access the definitions within it, as explained before. Here’s an illustration.

# import statement example
# to import standard module math

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

When you run the program, the output will be:

The value of pi is 3.141592653589793

Import with renaming

We can import a module by renaming it as follows:

# import module by renaming it

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

The math module has been renamed to m. In some circumstances, this can save us time typing.

It’s worth noting that the term “math” isn’t used in our context. As a result, math.pi is incorrect, whereas m.pi is correct.

Python from…import statement

We can import particular names from a module rather than the entire module. Here’s an example.

# import only pi from math module

from math import pi
print("The value of pi is", pi)

Only the pi attribute from the math module was imported in this case.

We don’t utilize the dot operator in these circumstances. Multiple attributes can also be imported, as shown below:

>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045

Import all names

Using the following construct, we may import all names(definitions) from a module:

# import all names from the standard module math

from math import *
print("The value of pi is", pi)

All of the definitions from the math module have been imported here. Except for those that begin with an underscore, this contains all names visible in our scope (private definitions).

Using the asterisk (*) sign to import everything is not a smart programming practice. This can result in several identifier definitions. It also makes our code more difficult to read.


Python searches in numerous places when importing a module. The interpreter looks for a built-in module first. Python then searches a list of directories defined in sys.path if a built-in module isn’t found. This is the order of the search.

  • The location of the current directory.
  • PYTHONPATH is a Python path (an environment variable with a list of directories).
  • The default directory, which varies depending on the installation.
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

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


Reloading a module

During a session, the Python interpreter only imports a module once. Things become more efficient as a result of this. To see how this works, consider the following example.

Assume the following code is in a module called my module.

# This module shows the effect of
#  multiple imports and reload

print("This code got executed")

Now we see the effect of multiple imports.

>>> import my_module
This code got executed
>>> import my_module
>>> import my_module

We can see that our code was only run once. This means that our module was only imported once.

We’d have to reload our module if it changed during the course of the application.

Restarting the interpreter is one way to do this. However, this is of little use.

Python offers a more efficient method of accomplishing this. To reload a module, we can use the imp module’s reload() function. We can do it in a variety of ways:

>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed
<module 'my_module' from '.\\my_module.py'>

The dir() built-in function

The built-in method dir() returns a sorted list of strings containing a module’s names.

The names of all the modules, variables, and functions defined in a module are listed in this list. Here’s a simple illustration:

>>> dir(example)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
'add']

A sorted list of names (along with add) can be found here. All other names that begin with an underscore are the module’s default Python attributes (not user-defined).

The name element, for example, contains the module’s name.

>>> import example
>>> example.__name__
'example'

The dir() method can be used without any arguments to find all the names defined in our current namespace.

>>> a = 1
>>> b = "hello"
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']

Leave a Comment

Your email address will not be published.