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 ...

Get Modular Programming with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.