Modules

Python Packages

Creating Python Packages

Python packages organize modules, using __init__.py files.

Introduction to Python Packages

In Python, a package is a way of organizing related modules into a single directory hierarchy. Packages allow for a hierarchical structuring of the module namespace using dot notation. This makes it easier to manage large codebases and avoid module name conflicts.

Creating a Python Package

To create a package, you need to organize your modules into a directory and include a special file named __init__.py. This file can be empty but must be present in order for Python to recognize the directory as a package.

The Role of __init__.py

The __init__.py file can be used to execute initialization code for the package or to set the __all__ variable, which determines what is imported when from package_name import * is used. If you don't need any initialization code, the file can simply be an empty placeholder.

Importing from Packages

Once you have a package, you can import modules from it using dot notation. For example, if you have a package named my_package, you can import module1 as follows:

Example of a Package Structure

Let's consider a simple example of a package that contains two modules and an initialization script. This package provides basic mathematical operations.

The addition.py module might look like this:

And the subtraction.py module could be implemented as:

The __init__.py could be used to import these functions for easier access:

Conclusion

Python packages are a powerful tool for organizing and managing code, especially as projects grow in size and complexity. By using packages, you can keep your code modular and maintainable, while also avoiding naming conflicts.

Previous
Modules