/ Published in: Python
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.
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
x = 1 def fun(a): b=3 x=4 def sub(c): d=b global x x = 7 print ("Nested Function\n=================") print locals() sub(5) print ("\nFunction\n=================") print locals() print locals()["x"] print globals()["x"] print ("\nGlobals\n=================") print globals() fun(2) ///scope.py Globals ================= {'x': 1, '__file__': 'C:\\books\\python\\CH1\\code\\scope.py', 'fun': <function fun at 0x008D7570>, 't': <class '__main__.t'>, 'time': <module 'time' (built-in)>,. . .} Nested Function ================= {'c': 5, 'b': 3, 'd': 3} Function ================= {'a': 2, 'x': 4, 'b': 3, 'sub': <function sub at 0x008D75F0>} 4 7