Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Renaming an Imported Module
00:00
The import statement is quite flexible. There are four variations that you should know about. First, import <module>, import <module> as <other_name>, from <module> import <name>, and from <module> import <name> as some other name.
00:16
You already worked with the first import statement. Let’s look at the three other import statement variations in detail.
00:25
With an import statement that looks like this—import <module> as some other module name—you can change the name of an import when you import a module.
00:35
This way, the module’s namespace is accessed through <other_name> instead of <module>. So how does this look in action?
00:46
In your project, change the import statement in main.py to the following: import adder as a, and then leave the code below unchanged.
00:58
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.
01:14
Therefore, the adder name doesn’t exist anymore and it’s no longer recognized. To make main.py work, you need to replace adder.add() and adder.double() with a.add() and a.double().
01:30
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 double_value to a.double().
01:47 Now save the file and run the module.
01:51
No NameError is raised, and the values 4 and 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.
02:03 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.
Become a Member to join the conversation.