Python Modules
What is a module in Python?
A module is a file containing Python definitions and statements.
Modules are used:
- to break down large programs into small manageable and organized files.
- to provide reusability of code.
- to be imported into different programs.
How to create modules in Python?
To create a module, simply save the desired code in a file with the .py
extension.
For example, create mymodule.py
:
# Python Module mymodule
def add(a, b):
"""This function sums two numbers and returns the result"""
return a + b
def say_hello(name):
return f"Hello {name}"
How to import modules in Python?
To use the definitions of a form, you must import that module!
Python Standard Modules can be imported in the same way as user-defined modules.
Listed below are the various ways to import modules.
Python import statement
The import
statement is used to import a module and then access the definitions inside it using the .
(dot) operator.
import mymodule
result = mymodule.sum(1 + 2)
print(result) # 3
It does not import the names of functions defined in mymodule
directly into the current symbol table. It imports only the name of the mymodule
module.
Import with renaming
A module can be imported and be renamed using as
keyword.
For example, import mymodule.py
module and rename it to m
import mymodule as m
result = m.sum(1 + 2)
print(result) # 3
Once the name is changed, only the new alias can be used to refer to the definitions contained in the module.
Python from...import statement
You can import specific names from a module without importing the module as a whole.
For example, import the pi
and e
attributes from the math
module.
from math import pi, e
print("The value of pi is", pi)
print("The value of e is", e)
In these cases, the dot .
operator is not used.
Import all names
You can import all name definitions from a module using the *
symbol in this way:
from math import *
print("The value of pi is", pi)
print("The value of pi is", e)
With *
you import all the definitions from the math
module.
Importing everything with an asterisk *
symbol is not good programming practice because it can lead to duplicate identifier definitions and reduce code readability.
Python Module Search Path
The Python Interpreter looks at several places while importing a module.
First, it looks for a built-in module. Then, if the built-in module is not found, it searches into a directory list defined in sys.path
.
In summary, the search is in this order:
- The current directory.
PYTHONPATH
(an environment variable with a list of directories).- The installation-dependent default directory.
Example of what you can find in sys.path
(varies depending on the system)
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
Using the dir() Function
The dir()
function is used to find out names that are defined inside a module.
The dir()
function can be used on all modules, even those created by the user.
For example, this is what math
module contains (output of dir(math)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
All names beginning with an underscore are default Python attributes associated with the module.