Importing Objects From a Module
And you see
4 and the
8 are printed. So your file works perfectly. And now let’s try something else. Still in
main.py, change the
import statement to the following:
import add, then save the file.
That means you can use the
add() function without having to type
adder.add(), or, let me rephrase that. You actually must use the
add() function without putting
adder and the dot before the function name. So let’s update the code accordingly.
Okay. So this time the
NameError tells you that the name
double isn’t defined. And if you have a look at the import statement, then you can verify that yeah, indeed we only imported
add but not
So when you write import statements like this, you gain control over which names from the module you want to import. So with
from adder import add, only the
add name was imported from the
adder module. To also import the
double name, you put a comma after it and then write
So the line now is
import add, double. Save and run the module. Now the module runs without producing a
4 and the
8 are printed in the interactive window. Perfect. Now that the code works, it’s time to show another slide.
Become a Member to join the conversation.