
PYTHON — Creating Python Packages
Programming isn’t about what you know; it’s about what you can figure out. — Chris Pine
Creating Python Packages
In this tutorial, you will learn how to create Python packages. A Python package is a way of organizing related modules into a single directory hierarchy. This allows you to structure your Python projects and reuse code across multiple projects.
Creating a Package Structure
To create a Python package, start by creating a project folder. In your terminal or file explorer, navigate to the location where you want to create the package. Then, create a folder to serve as the project root folder. For example, you can create a folder named packages_example/.
Inside the packages_example/ folder, create another folder and name it mypackage/. This mypackage/ folder will eventually become a Python package, but it's not a package yet because it doesn't contain any modules.
To turn mypackage/ into a Python package, you need to create an __init__.py file inside it. This file can be empty, but it's necessary for Python to recognize the folder as a package. You can create an empty __init__.py file using a text editor or an integrated development environment (IDE).
Next, create two Python files inside the mypackage/ folder: module1.py and module2.py. These files will be the modules inside the package.
In module1.py, define a function called greet that takes a name parameter and prints a personalized greeting using an f-string:
# module1.py
def greet(name):
print(f"Hello, {name}!")In module2.py, define a function called depart that also takes a name parameter and prints a farewell message using an f-string:
# module2.py
def depart(name):
print(f"Goodbye, {name}!")With this folder structure and the module files in place, you have successfully created a Python package.
Importing and Using the Package
Now that you have created the package, you can import and use the modules in another Python file. To do this, simply use the import statement and the name of the package and module:
# main.py
import mypackage.module1
import mypackage.module2
mypackage.module1.greet("Alice")
mypackage.module2.depart("Bob")In this example, main.py imports the module1 and module2 from the mypackage package and then calls the greet and depart functions to display the personalized messages.
By following these steps, you have successfully created a Python package with modules and used it in another Python file.
Conclusion
In this tutorial, you learned how to create a Python package and its structure, including the use of __init__.py and module files. You also learned how to import and use the package in another Python file. Python packages are a powerful way to organize and share code, and by mastering their creation, you can improve the structure and reuse of your Python projects.






