Return to Snippet

Revision: 21861
at December 22, 2009 15:25 by magicrebirth

Initial Code
x = 1
def fun(a):
    def sub(c):
        global x
        x = 7
        print ("Nested Function\n=================")
        print locals()

    print ("\nFunction\n=================")
    print locals()
    print locals()["x"]
    print globals()["x"]

print ("\nGlobals\n=================")
print globals()



{'x': 1,
 'fun': <function fun at 0x008D7570>,
 't': <class '__main__.t'>,
 'time': <module 'time' (built-in)>,. . .}

Nested Function
{'c': 5, 'b': 3, 'd': 3}

{'a': 2, 'x': 4, 'b': 3, 'sub':
    <function sub at 0x008D75F0>}

Initial URL

Initial Description
Scoping in Python revolves around the concept of namespaces. Namespaces are basically dictionaries containing the names and values of the objects within a given scope. There are four basic types of namespaces that you will be dealing with: the global, local, module, and class namespaces.

Global namespaces are created when a program begins execution. The global namespace initially includes built-in information about the module being executed. As new objects are defined in the global namespace scope, they are added to the namespace. The global namespace is accessible from all scopes, as shown in the example where the global value of x is retrieved using globals()["x"].

Local namespaces are created when a function is called. Local namespaces are nested with functions as they are nested. Name lookups begin in the most nested namespace and move out to the global namespaces.

The global statement forces names to be linked to the global namespace rather than to the local namespace. In the sample code, we use the global statement to force the name x to point to the global namespace. When x is changed, the global object will be modified.

Initial Title
Python: local and global namespaces

Initial Tags

Initial Language