How Modules Actually Work in Python and How to Create Your Own Custom Module (81/100 Days of Python)
Python is a powerful programming language that supports modularity, which means you can organize your code into separate, reusable units called modules. Modules allow you to encapsulate code and reuse it in different parts of your program or in different programs altogether. In this tutorial, we will explore the basics of modules in Python, including import syntax and how modules work.
What is a Module?
A module in Python is a file containing Python definitions and statements. A module can define functions, classes, and variables, and it can also include executable code. You can use a module in your code by importing it. Python comes with many built-in modules, such as the math module, that you can use in your code without having to write any extra code.
Importing Modules
To use a module in your code, you need to import it. The syntax for importing a module is:
import module_name
For example, to import the math
module, you would use:
import math
Once you have imported a module, you can use its functions and variables by prefixing them with the module name. For example, to use the pi
constant from the math
module, you would use:
import math
print(math.pi)
This would output the value of pi
.
From X import Y Syntax
Sometimes, you might only want to import specific functions or variables from a module, rather than importing the entire module. In this case, you can use the from X import Y
syntax. The syntax for using this syntax is:
from module_name import function_name
For example, to import only the pi
constant from the math
module, you would use:
from math import pi
print(pi)
This would output the value of pi
.
You can also import multiple functions or variables from a module by separating them with commas, like this:
from math import pi, sqrt
print(pi)
print(sqrt(4))
This would output the value of pi
and the square root of 4.
From X import * Syntax
In Python, the from X import *
syntax allows you to import all functions and variables from a module into your current namespace. This means that you can use the imported functions and variables without prefixing them with the module name. For example, if you import all functions and variables from the math
module, you could use pi
directly, like this:
from math import *
print(pi)
However, using the from X import *
syntax is generally not recommended for several reasons.
First, it can make your code harder to read and understand. When you use the from X import *
syntax, it’s not always clear where a function or variable is coming from. This can make it difficult to trace the source of bugs and errors in your code.
Second, it can lead to naming conflicts. If you import all functions and variables from two different modules that have the same name, you’ll end up with naming conflicts. For example, if you import all functions and variables from both the math
module and the statistics
module, you’ll end up with two functions named fabs()
. This can cause confusion and errors in your code.
Third, it can make your code less efficient. When you use the from X import *
syntax, Python has to load and compile all the functions and variables from the module, even if you’re only going to use a few of them. This can slow down the loading time of your program and use up more memory than necessary.
In general, it’s better to be explicit about which functions and variables you’re importing from a module. This makes your code easier to read and understand, reduces the risk of naming conflicts, and can make your code more efficient. If you need to import a large number of functions and variables from a module, it’s better to import them explicitly, like this:
from math import pi, sin, cos, tan
This way, you can be sure which functions and variables you’re using and avoid naming conflicts.
How Modules Work in Python
When you import a module in Python, the interpreter searches for the module in the following locations:
- The current directory
- The directories listed in the
PYTHONPATH
environment variable - The installation-dependent default directory
Once the interpreter finds the module, it compiles it into a bytecode file (with a .pyc
extension) and stores it in the __pycache__
directory. This bytecode file is used to speed up subsequent imports of the module.
When you import a module, Python creates a new namespace for the module, which acts as a separate environment for the module’s variables, functions, and classes. This namespace is represented by a dictionary, and it is stored in the sys.modules
dictionary.
How to Create Your Own Module in Python
A module in Python is simply a file with a .py
extension that contains Python code. To create a module, you just need to write your code in a .py
file and save it with an appropriate name.
Let’s create a file named circle.py
and place the following code in it:
import math
def area_of_circle(radius):
return math.pi * radius ** 2
Now, you can use this module in your other Python programs by importing it. In another file called main.py
, we can import the circle and use its functionality:
import circle
area = circle.area_of_circle(radius=5)
print(f'The area of a circle with radius {radius} is {area}')
In this example, we import the circle module and use its area_of_circle
function to calculate the area of a circle with a radius of 5. We then print the result.
Note that if the circle
module is in some subdirectory, we should import it indicating the full path from the main.py
— that can look something like the following:
from geometry.objects import circle # /geometry/objects/circle.py
from shapes import circle # /shapes/circle.py
import circle # /circle.py
We will discuss how to create a project with a proper structure, that would make working with different modules easy and intuitive, in the coming series.
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course
- Full series: 100 Days of Python
- Previous topic: Multithreading VS Multiprocessing VS Asyncio in Python
- Next topic: What are Packages in Python and What is the Role of __init__.py files?