Python - Module Module Initialization


Because top-level code in a module file is usually executed only once, you can use it to initialize variables.

Consider the file, for example:

test = 1                   # Initialize variable 

In the following example, the print and = statements run the first time the module is imported, and the variable test is initialized at import time:

import simple          # First import: loads and runs file's code 
#output: hello 

print(simple.test)            # Assignment makes an attribute 
#output: 1 

imports don't rerun the module's code, they just fetch the already created module object from Python's internal modules table.

Thus, the variable test is not reinitialized:

simple.test = 2        # Change attribute in module 
import simple          # Just fetches already loaded module 
simple.test            # Code wasn't rerun: attribute unchanged 

Related Topics