Table of contents
What is a Module?
A Python module is a file containing Python definitions and statements.
It's a way of organizing related code into a single file, making the code easier to understand and use.
A module can define functions, classes, and variables that can be utilized in other
Python programs via the import statement. It can also include runnable code.
The name of the module is the same as the filename (without the .py
extension).
Modules are a vital aspect of Python programming as they promote code reusability and keep the codebase
organized and manageable.
Basic Example
Let's create a module, which will be a file named utils.py, and populate it with the following code:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
and now let's create another file named main.py and import the utils.py module:
import utils
print(utils.add(5, 3))
print(utils.subtract(5, 3))
When you run the main.py file, you should see the following output:
8
2
If you already have a module with the same name as a built-in module, you can use the as
keyword to rename the module:
import math as my_math
print(my_math.pi)
When you run the main.py file, you should see the following output:
3.141592653589793
Module Name
To get a module name in Python, you can use the __name__
attribute.
When a module is imported, Python sets the __name__
attribute to the name of the module.
import utils
print(utils.__name__)
Which will output:
utils
File path
There is also the __file__
attribute, which contains the path to the module file.
import utils
print(utils.__file__)
The function print(utils.__file__)
will return the path to the source file of the utils
module.
This is useful when you want to know the exact location of the module's source code in your file system.
The __file__
attribute is a built-in attribute in Python that's automatically set to the path of the module when it's loaded.
By printing this attribute, you can see where the Python interpreter found the module when it was imported.
To get the absolute path of the module, you can use the os
module:
import os
import utils
print(os.path.abspath(utils.__file__))
When you run the main.py file, you should see the absolute path to the utils.py file.
Using specific functions and variables from a module
Each module has its own private namespace, which means that the functions, classes, and variables defined in the module are not accessible from the outside unless explicitly imported. That means we can have multiple variables without worrying about naming conflicts.
To use specific functions and variables from a module, you can import them individually. Let's first modify the utils.py file to include a variable:
PI = 3.14159
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Now, let's import the add
function and the PI
variable from the utils.py module:
from utils import add, PI
print(add(5, 3))
print(PI)
When you run the main.py file, you should see the following output:
8
3.14159
If you want to import all functions and variables from a module, you can use the *
operator:
from utils import *
print(add(5, 3))
print(subtract(5, 3))
print(PI)
When you run the main.py file, you should see the following output:
8
2
3.14159
Importing a function from a module using an alias
But what if you already have a function or variable with the same name in your file?
You can use the as
keyword to rename the imported function or variable:
from utils import add as addition
print(addition(5, 3))
When you run the main.py file, you should see the following output:
8
Executable module
A module can be run as a standalone program by adding the following code at the end of the module:
if __name__ == "__main__":
print("This is the main module")
In this case, the module name isn't the file name, but __main__
.
Also, the code inside the if __name__ == "__main__":
block will only run if
the module is executed as the main program.
Built-in modules
Python comes with a set of built-in modules that provide access to system functionality, like file I/O, networking, and more.
You can find a list of built-in modules in the Python documentation.
If we need to figure out what a module does, we can use the help
function:
import math
help(math)
Which will output:
Help on module math:
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
The result is between 0 and pi.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
asin(x, /)
Return the arc sine (measured in radians) of x.
The result is between -pi/2 and pi/2.
...
Another useful function is dir
, which lists all the functions and variables in a module:
import math
print(dir(math))
Which will output:
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt
', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fm
od', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log1
0', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'sumprod', 'tan',
'tanh', 'tau', 'trunc', 'ulp']