A fundamental aspect of programming in Python is the concept of modules and packages. Modules are Python files that contain functions, classes, and variables that can be imported and used in other programs. Packages are a way to organize related modules into a single directory structure. This chapter of the e-book course will cover the creation and organization of modules and packages in Python for the creation of systems with Python and Django.
10.3.1. Creating Modules in Python
Creating a module in Python is simple. All you need to do is create a new .py file and write your Python code inside it. For example, you can create a module called "math_operations.py" that contains functions to perform basic math operations.
# math_operations.py def add(a, b): return a + b def subtract(a, b): return a - b
Once you create the module, you can import it and use its functions in other Python programs.
# main.py import math_operations print(math_operations.add(5, 3)) # Outputs: 8 print(math_operations.subtract(5, 3)) # Outputs: 2
10.3.2. Creating Packages in Python
A package in Python is simply a folder that contains various modules. To create a package, you need to create a new folder and add a special file called "__init__.py" inside it. This file can be empty, but it must be present for Python to recognize the folder as a package.
For example, you can create a package called "operations" that contains the "math_operations.py" module we created earlier.
operations/ __init__.py math_operations.py
You can now import the "math_operations" module from the "operations" package as follows:
# main.py from operations import math_operations print(math_operations.add(5, 3)) # Outputs: 8 print(math_operations.subtract(5, 3)) # Outputs: 2
10.3.3. Organizing Packages in Python
Python packages can contain other packages, allowing you to organize your modules in a hierarchical directory structure. This is common practice in large-scale Python projects, as it makes code easier to organize and manage.
For example, you might have a "math" package that contains an "operations" subpackage, which in turn contains the "math_operations" module.
math/ __init__.py operations/ __init__.py math_operations.py
You can import the "math_operations" module from the "operations" subpackage of the "math" package as follows:
# main.py from math.operations import math_operations print(math_operations.add(5, 3)) # Outputs: 8 print(math_operations.subtract(5, 3)) # Outputs: 2
In short, modules and packages are powerful tools that let you organize and reuse Python code. They are key to building efficient, well-organized systems with Python and Django. In the next chapter, we'll cover creating classes and objects in Python, which are fundamental concepts of object-oriented programming.