Working With Packages
To see how importing a module from a package works, create another IDLE editor window. And there you will create your calling module. At the beginning of the file, you import the package with
Before adding any more code, just save this file for now. Name it
main.py, and now it’s important you save it in your project folder. That means
main.py is not in the same folder as
module2, but in the parent folder that you named
Let’s see what happens when you run
main.py. Oh, hello there. No error at all. That’s a new one. That means importing your package works. Let’s continue with
main.py, and as a little heads up, with the code changes you’re adding now, we’ll get an error soon.
main.py and run the module. And as promised, there is an error. But have a closer look. This time, it’s not a
NameError like we had in the former lessons. In the interactive window, An
AttributeError is raised.
AttributeError: module 'mypackage' has no attribute 'module1'.
So when you import the
mypackage module, the
module2 namespaces aren’t imported automatically, so you need to import them too. And for this, you adjust the
import statement at the beginning and use two new
import statements instead.
So you type the name of the package, followed by a dot, and then the name of the module you want to import. In this case, for both
import statements, the package name is
mypackage, and then you add a dot, and after the dot,
module1 in the first line, and in the second line, you use
module2 as the module name after the dot.
Become a Member to join the conversation.