Chapter 7: Modules and Packages
In Python, modules and packages help organize code, promote reusability, and manage complexity in large projects. A module is a file containing Python code, and a package is a collection of modules organized in directories.
Modules
A module is simply a Python file with a .py
extension. Modules can contain functions, classes, and variables that can be reused in other scripts.
Creating and Importing a Module
Create a Module: Save the following as
mymodule.py
:Import the Module: Use the
import
keyword to use the module in another script.Import Specific Items: Use the
from
keyword to import specific elements.Alias Modules: Use the
as
keyword to give a module an alias.
Built-in Modules
Python comes with a rich standard library of built-in modules. Some commonly used modules include:
Module
Description
math
Mathematical functions and constants.
os
Interacting with the operating system.
sys
Accessing system-specific parameters.
random
Generating random numbers.
datetime
Working with dates and times.
Example:
Packages
A package is a collection of related modules grouped into a directory. It contains an __init__.py
file, which can be empty or include package initialization code.
Creating a Package
Create a directory named
mypackage
.Add an empty
__init__.py
file to the directory.Add modules to the package:
module1.py
:module2.py
:
Import and use the package:
Nested Packages
Packages can contain sub-packages for better organization.
The __name__
Variable
__name__
VariableEvery Python module has a special variable __name__
. When a module is run directly, __name__
is set to "__main__"
. This is useful for writing code that behaves differently when a module is imported versus executed directly.
Example:
Exercises
Exercise 1:
Create a module calculator.py
with functions add
, subtract
, multiply
, and divide
. Use it in another script.
Solution:
Exercise 2:
Create a package shapes
with modules circle
and rectangle
. Implement functions to calculate the area of each shape.
Solution:
Best Practices
Use meaningful names for modules and packages.
Avoid circular imports (modules importing each other).
Keep modules small and focused on a specific task.
Use packages to organize related functionality.
In the next chapter, we will explore file handling, including reading, writing, and managing files in Python.
Last updated