Renaming an Imported Module
import statement is quite flexible. There are four variations that you should know about. First,
import <module> as <other_name>,
from <module> import <name>, and
from <module> import <name> as some other name. You already worked with the first
Save the file and run it. Now a
NameError is raised:
NameError: name 'adder' is not defined. The reason why Python raised this
NameError is because the module has been imported with the name
a instead of
adder. Therefore, the
adder name doesn’t exist anymore and it’s no longer recognized.
main.py work, you need to replace
a.double(). So let’s do that. In the line after the
import statement, you change the value to
a.add(), and in the line below, you change the value of
NameError is raised, and the values
8 are printed in the interactive window. So changing the name of an import can be handy when you want to make a name unique or shorten long module names. For example, if you are importing a module, and the module’s name is a name that you already have for a variable, then it can make sense to rename the module that you’re importing to a different name.
02:16 But usually, you rename a module that you’re importing because the name of the module that you’re importing is very long. So shortening can make sense. However, you could argue that shortening the name to a single letter isn’t particularly descriptive, and it’s not super short, as you still need the notation in front of the function name. So let’s have a look at another import variant.
Become a Member to join the conversation.