We will learn to create a module in python and also custom modules in Python in this blog. You can learn different methods on how to import modules through different methods we give a complete guide on modules and how they work. So, let’s dive into how to create a module in python.
What are modules in Python?
You can say that Modules are a type of file containing Python statements and definitions. Different types of the file containing Python code, for example:
example.py, is called a module, and its module name would be
You can use modules to help break down big heavy programs into smaller manageable and organized files that you can use easily. Also, they also provide the function where you can use the code again.
We can define our most used functions in a module and import them, instead of copying their definitions into different programs.
Let us create a module. Type the following and save it as
# Python Module example def add(a, b): """This program adds two numbers and return the result""" result = a + b return result
Now here, we have defined a function
add() inside a module named
example. This function takes in two different numbers and returns their sum.
How to import Module in Python?
You can import this definition inside a module to another module or the interactive interpreter in Python.
import keyword to do this. For the import from the previously defined example, you can type the following in the python prompt.
>>> import example
This does not import the names of the functions defined in example directly in the current symbol table. It only imports the module name example there.
If you use this module name then you can access the function using the dot
. operator. For example:
Python has tons of different modules. You can also check out the full lost of Python standard modules and their use cases. These files are in the Lib directory inside the location where you installed Python.
Standard modules can be imported the same way as we import our user-defined modules.
There are many different ways by which you can import modules. They are listed below
Python import statement
We can easily import a module using the
import statement and can also access the definitions inside it using the dot operator as we described above. Let’s see it with an example:
# import statement example # to import standard module math import math print("The value of pi is", math.pi)
After you run the program the output will be:
The value of pi is 3.141592653589793
Import with Renaming:
You can also 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)
As you can see we have renamed the
math module as
m . You can save typing time in such cases. If you are writing a big program this can be useful.
You can also see that the name math is not recognized in our scope. Hence you can see the name
math.pi is invalid and the new name
m.pi is the correct implementation.
Python from import statement
You can also import specific names from a module without importing the whole module which can be a time saving thing. You can see that down below from the example we have provided.
# import only pi from math module from math import pi print("The value of pi is", pi)
Now here we have imported the
pi attribute from the
In these cases you don’t have to use the dot operator. You can also import multiple attributes very easily as follows:
>>> from math import pi, e >>> pi 3.141592653589793 >>> e 2.718281828459045
You can Import all Names:
It easy to import all the names(Definitions) from a module using the following construct:
# import all names from the standard module math from math import * print("The value of pi is", pi)
Here you can see we have imported all the definitions from the math module. This includes all names in our scope except those beginning with an underscore.
You can import everything with the asterisk(*) symbol is not a good Programming practice. That can lead to duplicate definitions for an identifier. This can also hampers the readability of the code.
Python Module Search Path:
Python looks for module as several places before trying to import the module but interpreter first looks for a built-in module. Then after the built–in module is not found python looks into a list of several other directories defined in
sys.path. The search is in this order.
- The current directory
PYTHONPATH(an environment variable with a list of directories).
- The installation-dependent default directory.
>>> 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']
You can also add and modify this list to add to your own path.
Reloading a module
The Python interpreter imports a module only once during a session. This makes this more easy and efficient. Here is an example to show how this thing will work.
Suppose we have the following code in a module named
# This module shows the effect of # multiple imports and reload print("This code got executed")
Now you can also see how it affects multiple reports:
>>> import my_module This code got executed >>> import my_module >>> import my_module
You can see that the code only got executed once. From this we can say that our module was imported only once.
Now if you see the module changing during the course of the program, you would have to reload the module again. One way you can do this is to restart the interpreter again. But we can say that this will not help you much.
Python provides a more efficient way of doing this. We can use the
reload() function inside the
imp module to reload a module. We can do it in the following 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
We can use the dir() function to find out names that are only defined inside a module.
Let us give you an example so we have defined a function
add() in the module
example that we had in the beginning.
You can also use
example module in the following way:
>>> dir(example) ['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', 'add']
Now here you can see the list of sorted names (along with
add). And you can all the other names with underscore are default Python attributes associated
with the module (not user-defined).
For example, the
__name__ the attribute contains the name of the module.
>>> import example >>> example.__name__ 'example'
Now as you can see the names defined in our current namespace can be found out using the
dir() function without any arguments.
>>> a = 1 >>> b = "hello" >>> import math >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']
Create a module in python and are you having problems with that. We have given the different options by which you can create a module in python. Hope you find this information useful. Thank you for the read.