Packages
In Python, packages are a way to organize related modules into a directory hierarchy. Packages allow for modular code organization, making projects more readable, reusable, and maintainable. A package is essentially a directory that contains a special __init__.py
file and one or more modules (Python files).
Packages are particularly useful for:
- Grouping related functionality.
- Avoiding module name conflicts in larger codebases.
- Providing a clear project structure.
Syntax
The structure of a Python package typically looks like this:
project_name/
package_name/
__init__.py # Marks the directory as a package (can be empty or include initialization code)
module1.py # First module in the package
module2.py # Second module in the package
main.py # Main program
- The
__init__.py
file is required to make Python treat the directory as a package. - Modules (
.py
files) inside the package can be imported and used in other parts of the project.
Importing a Package
To use a package or its modules, the syntax is:
import package_name.module_name
# OR
from package_name import module_name
# OR (import specific functions or classes)
from package_name.module_name import function_name, class_name
Example
Here’s an example that creates and uses a Python package:
Creating a Python Package
Create a directory with following files:
mypackage/__init__.pymodule1.pymodule2.py
__init__.py
: This file is used to indicate that the directorymypackage
is a package. It can be empty or contain initialization code for the package.module1.py
: A module within the package that could contain functions or classes.
# module1.pydef greet(name):return f"Hello, {name}!"
module2.py
: Another module within the package.
# module2.pydef farewell(name):return f"Goodbye, {name}!"
Using the Package
The package and its modules can then be used in another Python script like this:
# test_package.pyimport mypackage.module1 as m1import mypackage.module2 as m2print(m1.greet("Alice"))print(m2.farewell("Alice"))
The output of the above code will be as follows:
Hello, Alice!Goodbye, Alice!
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours