English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to create and import custom modules in Python. You will also discover different techniques for importing and using custom and built-in modules in Python.
A module is a file that contains Python statements and definitions.
Files containing Python code, such as example.py, are called modules, and their module name is example.
We use modules to break down large programs into manageable small files. In addition, modules provide code reusability.
We can define the most commonly used functions in the module and import them, rather than copying their definitions to other programs.
Let's create a module. Enter the following content and save it as example.py.
# Python module example def add(a, b): """This program adds two numbers" and return the sum result "" result = a + b return result
Here, we define an add() function in a module named example.Function. This function accepts two numbers and returns their sum.
We can import the definitions within a module into another module or the Python interactive interpreter.
We use the import keyword to do this. To import a module we previously defined, type the following at the Python prompt.
>>> import example
This will not directly input the defined function name into the current symbol table for example. It only inputs the module name here.
Using the module name, we can use the dot . operator to access functions. For example:
>>> example.add(4,5.5) 9.5
Python has a large number of available standard modules.
You can checkPython standard modulesThe complete list and their uses. These files are located in the Lib directory within the Python installation location.
Standard modules can be imported in the same way as user-defined modules.
There are multiple ways to import modules. They are listed as follows.
We can use the import statement to import modules and access their internal definitions using the dot operator, as shown above. This is an example.
# Example of import statement # Import standard module math import math print("The value of pi", math.pi)
When running this program, the output is:
The value of pi 3.141592653589793
We can rename the import module as follows.
# Rename module import import math as m print("The value of pi", m.pi)
We have renamed the math module to m. In some cases, this can save us writing time.
Note that the name math is not recognizable in our scope. Therefore, math.pi is invalid, while m.pi is the correct usage.
We can import specific names from a module without importing the module as a whole. This is an example.
# Import only pi from the math module from math import pi print("The value of pi", pi)
We only import the property pi from the module.
In this case, we do not use the dot operator. We can import multiple properties as follows.
>>> from math import pi, e >>> pi 3.141592653589793 >>> e 2.718281828459045
We can use the following construction to import all names (definitions) from a module.
# Import all names from the standard module math from math import * print("The value of pi", pi)
We import all definitions from the math module. This makes all names visible in our scope, except for those with underscores beginning.
Importing with an asterisk (*All the contents of the symbol are not a good programming habit. This may lead to duplicate definition of identifiers. It will also affect the readability of our code.
When importing modules, Python checks multiple locations. The interpreter first looks for a built-in module, and then (if not found) enters the defined directory list sys.path. The search is performed in this order.
Current directory.
PYTHONPATH (environment variable with directory list).
Default directories related to 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 or modify this list to add our own paths.
The Python interpreter imports a module only once during a session. This makes things more efficient. This is an example to illustrate how it works.
Suppose there is the following code in a module named my_module.
# This module displays # Multiple imports and re-importing print("This code has been executed")
Now we have seen the effect of multiple imports.
>>> import my_module This code is executed >>> import my_module >>> import my_module
We can see that our code has only been executed once. This indicates that our module has been imported only once.
Now, if our module changes during the execution of the program, we will have to reload it. One method is to restart the interpreter. But this does not help much.
Python provides a concise method. We can use the reload() function inside the module and the imp function to reload the module. How is this done.
>>> import imp >>> import my_module This code is executed >>> import my_module >>> imp.reload(my_module) This code is executed <module 'my_module' from '.\\my_module.py'>
We can use the dir() function to find names defined within the module.
For example, we defined an add() function in the starting module example.
>>> dir(example) ['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', 'add'
Here, we can see a sorted list of names (including add). All other names starting with an underscore are default Python attributes associated with the module (we did not define them ourselves).
For example, the __name__ attribute contains the name of the module.
>>> import example >>> example.__name__ 'example'
The dir() function without any parameters can be used to find all names defined in the current namespace.
>>> a = 1 >>> b = "hello" >>> import math >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']