Importing Modules

Importing a module requires the use of the import statement, whose syntax is:

import module1[, module2[, …moduleN]]
When this statement is encountered by the interpreter, the module is imported if found in the search path. Scoping rules apply, so if imported from the top-level of a module, it has global scope; if imported from a function, it has local scope. When a module is imported the first time, it is loaded and executed.

Importing vs. Loading

A module is loaded only once, regardless of the number of times it is imported. This prevents the module “execution” from happening over and over again if multiple imports occur. If your module imports the sys module, and so do five of the other modules you import, it would not be wise to load sys (or any other module) each time! So rest assured, loading happens only once, on first import.

Importing Module Attributes

It is possible to import specific module elements into your own module. By this, we really mean importing specific names from the module into the current namespace. For this purpose, we can use the from-import statement, whose syntax is:
from module import name1[, name2[, … nameN]]


You may also like...