An Overview of Python Modules, Packages, and Imports for Beginners
Written on
Chapter 1: Understanding Python Modules
In programming, a fundamental ability is crafting reusable code. This article provides a foundational understanding of Python modules and packages, along with an exploration of absolute and relative imports. In Python, code is organized into modules and packages.
What is a Python Module?
A module is simply a file that contains Python code, which may include functions, classes, and variables. Files with a .py extension are recognized as Python modules. You can create a module using any text editor. For instance, consider a file named sum_n.py that includes the following code:
To use the sum_n module in the Python interpreter, you would write:
import sum_n
To call the function sum_of_numbers, you would proceed as follows:
sum_n.sum_of_numbers([10, 13, 23, 24])
Alternatively, you can directly import the function:
from sum_n import sum_of_numbers
If you have multiple statements in sum_n.py, you can import everything from the module using:
from sum_n import *
This grants access to both the sum_of_numbers function and any classes defined within the module.
What is a Python Package?
A package is essentially a directory that contains multiple modules. In simpler terms, a package can be seen as a folder that may include subfolders, each housing their own modules. For example, the following structure represents a root package:
app/
__init__.py
models.py
views.py
util/
Python also provides built-in modules, such as the datetime module, which enables date and time manipulation. To utilize the datetime class, you would start by importing it:
from datetime import datetime
You can retrieve the current time with:
current_time = datetime.now()
print(current_time)
This will yield an output similar to:
2022-02-17 11:57:45.910122
Another built-in module is the math module, which allows for mathematical operations. For example, to access the value of pi, you would do:
import math
pi_constant = math.pi
print(pi_constant)
The output is:
3.141592653589793
Some modules require installation before use; for instance, to use matplotlib, you must first install it via pip:
pip install matplotlib
If you skip this step, you will encounter an import error:
ModuleNotFoundError: No module named 'matplotlib'
Importing Modules with Aliases
When module names are lengthy, you can create an alias using the as keyword. The syntax for this is:
import module_name as module_alias
For instance, to import the pyplot function as plt, you would write:
import matplotlib.pyplot as plt
plt.plot([10, 20, 30, 40])
plt.ylabel('Minimum values')
plt.show()
Organizing Imports
The Python PEP 8 style guide outlines several conventions for imports. The recommended order is:
- Standard library imports
- Third-party imports
- Local application imports
A blank line should separate each import group. Additionally, imports should be listed on separate lines, for example:
import os
import sys
Absolute Imports
Absolute imports specify the complete path to the function being imported, starting from the root directory. Consider creating a directory called my_project with the following structure:
my_project/
collection1/
__init__.py
file_a.py
collection2/
__init__.py
file_b.py
In file_a.py, you might define:
def english_greeting():
print("Long time, no see")
And in file_b.py, you could include:
def german_greeting():
print("Lange nicht gesehen")
To import these functions using the Python interpreter, you would write:
from collection1.file_a import english_greeting
from collection2.file_b import german_greeting
Relative Imports
Relative imports are designated based on the file's location from which they are being imported, utilizing dot notation. In a Django project, for example, the directory structure might look like this:
member_app/
Here’s how you would import the Member class in forms.py:
from .models import Member
Conclusion
As a Python developer, understanding modules, packages, and imports is crucial for writing efficient and scalable code. For more in-depth information, check out the official Python documentation.
More content at plainenglish.io. Sign up for our free weekly newsletter for exclusive writing opportunities and insights in our community Discord.