
PYTHON — Importing Modules from Subpackages in Python
Before software can be reusable it first has to be usable. — Ralph Johnson
Importing Modules From Subpackages in Python
One of the strengths of Python is its module and package system, which allows you to organize and structure your code effectively. In this tutorial, you will learn how to import modules from subpackages in Python.
Understanding Subpackages
A package in Python is essentially a folder containing one or more Python modules, with one module being the __init__.py file. Subpackages are packages nested inside another package, forming a hierarchical structure.
Let’s create an example package structure to understand how subpackages work.
Creating a Subpackage
- Create a
mypackage/folder with the files__init__.py,module1.py, andmodule2.py. - Inside the
mypackage/folder, create a subdirectory namedmysubpackage/. - Inside the
mysubpackage/folder, add an__init__.pyfile and a file namedmodule3.py.
Working With Subpackages
Now, let’s work with the created subpackage.
In the module3.py file, define a variable people as a list with four strings:
people = ["Christal", "Tappanita", "Martina", "Kate"]Next, in the main __init__.py file in the root directory of the package, remove any existing code and add the following:
from mypackage.module1 import greet
from mypackage.mysubpackage.module3 import people
for person in people:
greet(person)Here, the people list from module3 inside mysubpackage is imported using the dotted module name mypackage.mysubpackage.module3.
Running the Program
Save and run the main.py file. The output in the interactive window will be:
Hello, Christal!
Hello, Tappanita!
Hello, Martina!
Hello, Kate!This demonstrates how to work with subpackages in Python. Subpackages are beneficial for organizing code inside large packages. However, it’s essential to keep the folder structure clean and avoid deeply nested subpackages to prevent long dotted module names.
Conclusion
In this tutorial, you learned how to create and work with subpackages in Python to organize your code effectively. By understanding how to import modules from subpackages, you can enhance the structure and organization of your Python projects.
By following these practices, you can maintain a clean and manageable package structure in your Python projects.





