A.2 Namespaces and Bindings

The central concept in Python programming is that of a namespace. Each context (i.e., scope) in a Python program has available to it a hierarchically organized collection of namespaces; each namespace contains a set of names, and each name is bound to an object. In older versions of Python, namespaces were arranged according to the "three-scope rule" (builtin/global/local), but Python version 2.1 and later add lexically nested scoping. In most cases you do not need to worry about this subtlety, and scoping works the way you would expect (the special cases that prompted the addition of lexical scoping are mostly ones with nested functions and/or classes).

There are quite a few ways of binding a name to an object within the current namespace/scope and/or within some other scope. These various ways are listed below.

A.2.1 Assignment and Dereferencing

A Python statement like x=37 or y="foo" does a few things. If an object?e.g., 37 or "foo"?does not exist, Python creates one. If such an object does exist, Python locates it. Next, the name x or y is added to the current namespace, if it does not exist already, and that name is bound to the corresponding object. If a name already exists in the current namespace, it is re-bound. Multiple names, perhaps in multiple scopes/namespaces, can be bound to the same object.

A simple assignment statement binds a name into the current namespace, unless that name has been declared as global. A name declared as global is bound to the global (module-level) namespace instead. A qualified name used on the left of an assignment statement binds a name into a specified namespace?either to the attributes of an object, or to the namespace of a module/package; for example:

>>> x = "foo"              # bind 'x' in global namespace
>>> def myfunc():          # bind 'myfunc' in global namespace
...     global x, y        # specify namespace for 'x', 'y'
...     x = 1              # rebind global 'x' to 1 object
...     y = 2              # create global name 'y' and 2 object
...     z = 3              # create local name 'z' and 3 object
...
>>> import package.module  # bind name 'package.module'
>>> package.module.w = 4   # bind 'w' in namespace package.module
>>> from mymod import obj  # bind object 'obj' to global namespace
>>> obj.attr = 5           # bind name 'attr' to object 'obj'

Whenever a (possibly qualified) name occurs on the right side of an assignment, or on a line by itself, the name is dereferenced to the object itself. If a name has not been bound inside some accessible scope, it cannot be dereferenced; attempting to do so raises a NameError exception. If the name is followed by left and right parentheses (possibly with comma-separated expressions between them), the object is invoked/called after it is dereferenced. Exactly what happens upon invocation can be controlled and overridden for Python objects; but in general, invoking a function or method runs some code, and invoking a class creates an instance. For example:

>>> pkg.subpkg.func()   # invoke a function from a namespace
>>> x = y               # deref 'y' and bind same object to 'x'

A.2.2 Function and Class Definitions

Declaring a function or a class is simply the preferred way of describing an object and binding it to a name. But the def and class declarations are "deep down" just types of assignments. In the case of functions, the lambda operator can also be used on the right of an assignment to bind an "anonymous" function to a name. There is no equally direct technique for classes, but their declaration is still similar in effect:

>>> add1 = lambda x,y: x+y # bind 'add1' to function in global ns
>>> def add2(x, y):        # bind 'add2' to function in global ns
...     return x+y
...
>>> class Klass:           # bind 'Klass' to class object
...    def meth1(self):    # bind 'meth1' to method in 'Klass' ns
...        return 'Myself'

A.2.3 import Statements

Importing, or importing from, a module or a package adds or modifies bindings in the current namespace. The import statement has two forms, each with a bit different effect.

Statements of the forms

>>> import modname
>>> import pkg.subpkg.modname
>>> import pkg.modname as othername

add a new module object to the current namespace. These module objects themselves define namespaces that you can bind values in or utilize objects within.

Statements of the forms

>>> from modname import foo
>>> from pkg.subpkg.modname import foo as bar

instead add the names foo or bar to the current namespace. In any of these forms of import, any statements in the imported module are executed?the difference between the forms is simply the effect upon namespaces.

There is one more special form of the import statement; for example:

>>> from modname import *

The asterisk in this form is not a generalized glob or regular expression pattern, it is a special syntactic form. "Import star" imports every name in a module namespace into the current namespace (except those named with a leading underscore, which can still be explicitly imported if needed). Use of this form is somewhat discouraged because it risks adding names to the current namespace that you do not explicitly request and that may rebind existing names.

A.2.4 for Statements

Although for is a looping construct, the way it works is by binding successive elements of an iterable object to a name (in the current namespace). The following constructs are (almost) equivalent:

>>> for x in somelist:  # repeated binding with 'for'
...     print x
...
>>> ndx = 0             # rebinds 'ndx' if it was defined
>>> while 1:            # repeated binding in 'while'
...    x = somelist[ndx]
...    print x
...    ndx = ndx+1
...    if ndx >= len(somelist):
...        del ndx
...        break

A.2.5 except Statements

The except statement can optionally bind a name to an exception argument:

>>> try:
...     raise "ThisError", "some message"
... except "ThisError", x:    # Bind 'x' to exception argument
...     print x
...
some message