
PYTHON — Introducing Python Packages
Technology alone is not enough. It’s technology married with the liberal arts, married with the humanities, that yields the results that make our hearts sing. — Steve Jobs
Introducing Python Packages
In Python, a package is essentially a folder that contains one or more Python modules. Meanwhile, modules enable the division of a program into individual files that can be reused as needed. Organizing related code into a single module helps to keep it separate from other code, and packages take this organizational structure one step further.
To make a folder a regular Python package, the folder must contain an __init__ module. The __init__.py module doesn’t need to contain any code. It only needs to exist so that Python recognizes the folder as a Python package. Let's take a look at an example of a package structure and see how to create your first package.
# Package structure
mypackage/
__init__.py
module1.py
module2.pyTo create your first package, you can follow the steps below:
# Creating a package
# Create a folder named mypackage
# Inside mypackage, create an __init__.py file
# Inside mypackage, create module1.py and module2.py filesAfter creating the package structure, you can import modules and objects from the package using various methods. Here’s an example of importing modules and renaming objects using the as keyword:
# Importing modules and renaming objects
# from <package_name> import <module_name> as <new_name>
from mypackage import module1 as mod1
from mypackage import module2 as mod2
# Using objects from the imported modules
mod1.some_function()
mod2.some_other_function()You can also import specific objects from modules within the package using the following syntax:
# Importing specific objects from modules within the package
# from <package_name>.<module_name> import <object_name>
from mypackage.module1 import some_function
from mypackage.module2 import some_other_functionIn addition, you can import and use objects from modules within subpackages using the following syntax:
# Importing and using objects from modules within subpackages
# from <package_name>.<subpackage_name>.<module_name> import <object_name>
from mypackage.subpackage.module3 import another_functionUnderstanding how to create and work with packages in Python is essential for organizing and managing larger codebases. By following the steps outlined, you can start creating and utilizing packages in your Python projects.
