How to import anything
So far, we have used two different versions of the import
statement:
Importing a module and then using the module name to access something defined within that module. For example:
import math print(math.pi)
Importing something from a module and then using that thing directly. For example:
from math import pi print(pi)
The import
statement is very powerful, however, and we can do all sorts of interesting things with it. In this section, we will look at the different ways in which you can use the import
statement to import modules and packages, and their contents, into your program.
What does the import statement actually do?
Whenever you create a global variable or function, the Python interpreter adds the name of that variable or function to what is called the global namespace. The global namespace holds all the names that you have defined at the global level. To see how this works, enter the following command into the Python interpreter:
>>> print(globals())
The...