Summarizing Import Statements
Well, before showing you another slide, let me show you the slide from before. I was saying that there are four variations of the
import statement, and so far you’ve seen three, but there is a fourth one:
from <module> import <name> as <other_name>.
00:14 So this one is basically a combination of two and three. So you won’t see a demo for this one, but you can try it out yourself, and if something doesn’t work, just write in comments below. And now I will summarize the first three for you.
Again, the fourth variation isn’t in the summary because it’s a combination of the
import statements you are seeing in this slide. And this list summarizes what you’ve learned about importing modules so far.
The names are added to the calling module’s namespace and can be accessed directly. In your case, that was
from adder import add, double, and then you were able to access both functions directly by calling their names without any prefixes. In general,
import <module> is the preferred approach because it keeps the imported module’s namespace completely separate from the calling module’s namespace. Moreover, every name from the imported module is accessed from the calling module with the
<module>.<name> format, which immediately tells you in which module the name originates.
And the second reason is the module name clashes with an existing name in the calling module. The statement
import <module> as <other_name> still keeps the imported module’s namespace separate from the calling module’s namespace.
02:38 Importing specific names from a module is generally the least preferred way to import code from a module. The imported names are added directly to the calling module’s namespace, completely removing them from the context of the calling module.
import statements allow you to minimize the time you spend typing unnecessarily long dotted module names. That said, misusing the various
import statements can lead to a loss of context, resulting in code that is more difficult to understand.
Become a Member to join the conversation.