Modules

You can turn any valid source file into a module by loading it with the import statement. For example, consider the following code:

# file : spam.py
a = 37                    # A variable
def foo:                  # A function
    print "I'm foo"
class bar:                # A class
    def grok(self):
        print "I'm bar.grok"
b = bar()                 # Create an instance

To load this code as a module, you use the statement import spam. The first time import is used to load a module, it does three things:

  1. It creates a new namespace that serves as a namespace to all the objects defined in the corresponding source file. This is the namespace accessed when functions and methods defined within the module use the global statement.

  2. It executes the code contained in the module within the newly created namespace.

  3. It creates ...

Get Python: Essential Reference, Third Edition 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.