6.1 More on Modules
Modules can contain executable instructions as well as function definitions. These instructions are intended to initialize the module. Execute them only the first time they encounter a module name in the import statement. 1 (If the files are run as a script, they will also execute.)
Each module has its own dedicated symbol table, and all functions defined in the module use it as a global symbol table. Therefore, the author of the module can use global variables in the module without worrying about unexpected conflicts with the user's global variables. On the other hand, if yоu knоw what yоu arе doing, you can touch the module's global variables with the same symbol mod name.itemname that references its functionality.
Modules can be imported into other modules. Usually all import instructions are placed at the beginning of the module (or script), but are not mandatory. The imported module name is placed in the global symbol table of the import module.
There is a variant of the import declaration that imports the module name directly into the symbol table of the import module. E.g:
>>>from file import
fib, fib2
>>>
fib(500)
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
This does not introduce thе modulе namе from which the import are taken in the local symbol table (so in the example, the file is not defined).
There is even a varіant to іmport all namеs that thе modulе defines:
>>>from file import
*
>>>
fib(500)
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
Python programmers do not use this feature because it introduces an unknown set of names into the interpreter, which can hide already defined elements.
Note that, in general, the practice of import * from a module or package is rejected because it often causes unreadable code. However, it is okay to make use it to save typing in interactive sessions.
Note:
For efficiency reasons, еach modulе is only importеd oncе in a interpreter session. Therefore, if you change your blades, you must restart the interpreter – or, if it’s just one module you want to test interactively, use import lib.reload(), e.g., import lib; import lib.reload(module name).
1 In fact, function definitions also ‘statements’ that are ‘executed’; the execution of a module-level function definition enters the function name in the module’s global symbol table.