Calling an Imported Object
00:00
Make sure that you are in the editor window of IDLE for main.py
, and then add the following line to the top of the file: import
adder
.
00:12
So that’s basically the filename of the other file, only without the .py
extension. And that’s an important detail because the name you use to import the module adder
is the same as the module’s filename adder.py
. For this reason, module filenames must be valid Python identifiers.
00:31 That means they may only contain upper and lowercase letters, numbers, and underscores, and they may not start with a digit. These are the same rules for naming Python variables.
00:45
Add one blank line after the import
statement and leave the rest of your code unchanged. When you import one module into another, the contents of the imported module become available in the other.
00:58
The module with the import
statement is called the calling module. In this example, adder.py
is the imported module, and main.py
is the calling module.
01:10
The term calling module comes from the fact that you’re calling the imported function in this module. You’ve defined the function in adder.py
, but you’re calling it in main.py
, which makes main.py
the calling module.
01:26
Save main.py
and then run the module again.
01:31
Unfortunately, the NameError
exception is still raised. And the reason for this is because add()
can only be accessed from the adder
namespace. So what is a namespace?
Become a Member to join the conversation.