O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required