See All Titles |
![]() ![]() Importing ModulesImporting 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. Module "Executed" When LoadedOne effect of loading a module is that the imported module is "executed," that is, the top-level portion of the imported module is directly executed. This usually includes setting up of global variables as well as performing the class and function declarations, and if there is a check for __name__ to do more on direct script invocation, that is executed too. Of course, this type of execution may or may not be the desired effect. If not, you will have to put as much code as possible into functions. Suffice it to say that good module programming style dictates that only function and/or class definitions should be at the top-level of a module. Importing vs. LoadingA 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.
|
© 2002, O'Reilly & Associates, Inc. |