Initializing a module
When a module is imported, any top-level code within that module is executed. This has the effect of making the various functions, variables, and classes you defined in your module available for the caller to use. To see how this works, create a new Python source file named test_module.py
, and enter the following code into this module:
def foo(): print("in foo") def bar(): print("in bar") my_var = 0 print("importing test module")
Now, open up a terminal window, cd
into the directory where your test_module.py
file is stored, and type python
to start up the Python interpreter. Then try typing the following:
% import test_module
When you do this, the Python interpreter prints the following message:
importing test module
It does this because all the top-level Python statements in the module—including the def
statements and our print
statement—are executed when the module is imported. You can then call the foo
and bar
functions...