Importing Modules From Subpackages
And inside the
mysubpackage/ folder is another
__init__.py file and a file named
module3.py. A package nested inside another package is called a subpackage. In this example, the
mysubpackage/ folder is a subpackage of
mypackage/ because it contains an
__init__.py module as well as a second module called
module3.py. Let’s create the structure to see how it works.
So the place where you store those files is very important for this. In your
module3.py file, add the following code. Define a variable named
people that equals a list with four strings:
["Christal", "Tappanita, "Martina," "Kate"].
Remove any existing code that is in the
main.py file at this moment, and replace it with this code:
from mypackage.module1 import greet, and in the next line,
import people. An empty line, and then you loop through the list.
for person in people: and on the next line, indented,
03:11 Subpackages are great for organizing code inside very large packages. They help keep the folder structure of a package clean and organized. However, deeply nested subpackages introduce long dotted module names.
03:25 You can imagine how much typing it would take to import a module from a subpackage of a subpackage of a subpackage of a package. So it’s good practice to keep your subpackages at most one or two levels deep.
03:37 And it’s also a good practice to keep video courses on the shorter side, which is a great coincidence because let me look at my notes. There is not that much that I wanted to tell you today about modules and packages, but before we wrap up this course, I have a special treat for you in the next lesson.
Become a Member to join the conversation.