Introduction to Python: Class 4

Page Contents


Modules

Informally, a module is a bunch of Python code associated with a source file (but in fact Python is so dynamic that this needn't be strictly true).

A module is a code block, like a function body, but it is only executed once: upon import. A module has a name space; when the module's code block is executed, bindings occur in the module's name space. Attribute reference syntax is used to get at the module's name space, e.g.: m.x.

Predifined Module Attributes

A module has several predefined attruibutes:

Attribute Type Read/Write Description
__dict__ dictionary R/W The module name space.
__name__ string R/W The name of the module.
__doc__ string OR None R/W Module doc string.
__file__ string R/W Pathname of file from which modules was loaded.

The __name__ attribute will be set to the value "__main__" if you are executing code in the interactive interpreter and for a file foo loaded into the Python interpreter on the command line (e.g. python foo.py). This allows a useful bit of scaffolding in your modules: put this conditional at the end of your module:

      if __name__ == "__main__":
          ...
    

and put test code in the branch. Tnen when you load this file into the interpreter explicitly (as opposed to importing it), your test code will execute.

Importing

Modules are usually imported in order to use them. Importing a module has two steps:

  1. Find the module and execute the code within it
  2. Bind some names

Assume the module we're trying to import is called foo. To find it, Python searches for a file called foo.py in the directories named in the list sys.path. When found, the file is parsed and the code in it is executed. Any bindings that occur in the file happen in the modules name space. Some bindings also happen in the calling name space, depending on the form of the import statement:

      import module[, module]*
    

This form imports potentially several modules at once. Each module name is bound to that module.

      from module import name[, name]*
    

This form binds each name to module.name; the name module itself is not bound.

If an exception occurs in step 1, the bindings in step 2 are not made. When working interactively, you can fix the error in the module file and re-import. If the import was successful, and you make changes to the module, you cannot re-import; instead you should call the reload function with the module as an argument: reload(foo).

      from module import *
    

This form binds all the names in module in the calling name space; the name module itself is not bound. Note that it's possbile to bind hundreds of names with this command, possibly clobbering some things you wish had been left untouched. Use sparingly.

Exception Handling

There are two kinds of exceptions: implicit exceptions raised by the Python runtime system (e.g., ZeroDivisionError, MemoryError, KeyboardInterrupt), and explicit errors raised by the raise statement.

If an exception is not handled, Python will generate a backtrace, showing where the exception occurred; then, execution of the program is terminated (no termination if you're just typing at the interpreter).

The raise Statement

      raise expr[, parm[, traceback]]
    

The try Statement

      try:
          suite-1
      except [exception[, target]]:
          suite-i
      else:
          suite-n
    

The Standard Exception Hierarchy

Exception(*)
       |
       +-- StandardError(*)
            |
            +-- SystemExit
            +-- KeyboardInterrupt
            +-- ImportError
            +-- IOError
            +-- EOFError
            +-- RuntimeError
            +-- NameError
            +-- AttributeError
            +-- SyntaxError
            +-- TypeError
            +-- AssertionError
            +-- LookupError(*)
            |    |
            |    +-- IndexError
            |    +-- KeyError
            |
            +-- NumberError(*)
            |    |
            |    +-- OverflowError
            |    +-- ZeroDivisionError
            |    +-- FloatingPointError
            |
            +-- ValueError
            +-- SystemError
            +-- MemoryError