next up previous contents
Next: Exception Handling Up: Basic Principles of Python Previous: Object Oriented Programming   Contents


Namespaces and Variable Scoping

When you type the name of a variable inside a script or interactive python session, python needs to figure out exactly what variable you're using. To prevent variables you create from overwriting or interfering with variables in python itself or in the modules you use, python uses the concept of multiple namespaces. Basically, this means that the same variable name can be used in different parts of a program without fear of destroying the value of a variable you're not concerned with.

To keep its bookkeeping in order, python enforces what is known as the LGB rule. First, the local namespace is searched, then the global namespace, then the namespace of python built-in functions and variables. A local namespace is automatically created whenever you write a function, or a module containing any of functions, class definitions, or methods. The global namespace consists primarily of the variables you create as part of the ``top-level'' program, like a script or an interactive session. Finally, the built-in namespace consists of the objects which are part of python's core. You can see the contents of any of the namespaces by using the dir command:

>>> dir()
['__builtins__', '__doc__', '__name__']
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'EOFError', 
 'Ellipsis', 'Exception', 'FloatingPointError', 'IOError', 'ImportError', 
 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 
 'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError', 
 'StandardError', 'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 
 'ValueError', 'ZeroDivisionError', '_', '__debug__', '__doc__', 
 '__import__', '__name__', 'abs', 'apply', 'callable', 'chr', 'cmp', 
 'coerce', 'compile', 'complex', 'delattr', 'dir', 'divmod', 'eval', 
 'execfile', 'filter', 'float', 'getattr', 'globals', 'hasattr',
 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 
 'issubclass', 'len', 'list', 'locals', 'long', 'map', 'max', 'min', 
 'oct', 'open', 'ord', 'pow', 'range', 'raw_input', 'reduce', 'reload', 
 'repr', 'round', 'setattr', 'slice', 'str', 'tuple', 'type', 'vars', 
 'xrange']
The __builtins__ namespace contains all the functions, variables and exceptions which are part of python's core.

To give controlled access to other namespaces, python uses the import statement. There are three ways to use this statement. In its simplest form, you import the name of a module; this allows you to specify the various objects defined in that module by using a two level name, with the module's name and the object's name separated by a period. For example, the string module (Section 8.4) provides many functions useful for dealing with character strings. Suppose we want to use the split function of the string module to break up a sentence into a list containing separate words. We could use the following sequence of statements:

>>> import string
>>> string.split('Welcome to the Ministry of Silly Walks')
['Welcome', 'to', 'the', 'Ministry', 'of', 'Silly', 'Walks']
If we had tried to refer to this function as simply ``split'', python would not be able to find it. That's because we have only imported the string module into the local namespace, not all of the objects defined in the module. (See below for details of how to do that.)

The second form of the import statement is more specific; it specifies the individual objects from a module whose names we want imported into the local namespace. For example, if we only needed the two functions split and join for use in a program, we could import just those two names directly into the local namespace, allowing us to dispense with the string. prefix:

>>> from string import split,join
>>> split('Welcome to the Ministry of Silly Walks')
['Welcome', 'to', 'the', 'Ministry', 'of', 'Silly', 'Walks']
This technique reduces the amount of typing we need to do, and is an efficient way to bring just a few outside objects into the local environment.

Finally, some modules are designed so that you're expected to have top-level access to all of the functions in the module without having to use the module name as a prefix. In cases like this you can use a statement like:

>>> from string import *
Now all of the objects defined in the string module are available directly in the top-level environment, with no need for a prefix. You should use this technique with caution, because certain commonly used names from the module may override the names of your variables. In addition, it introduces lots of names into the local namespace, which could adversely affect python's efficiency.


next up previous contents
Next: Exception Handling Up: Basic Principles of Python Previous: Object Oriented Programming   Contents
Phil Spector 2003-11-12