Posted By

magicrebirth on 12/22/09


Tagged

python global local namespace


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

gartenstuhl


Python: local and global namespaces


 / 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.

  1. x = 1
  2. def fun(a):
  3. b=3
  4. x=4
  5. def sub(c):
  6. d=b
  7. global x
  8. x = 7
  9. print ("Nested Function\n=================")
  10. print locals()
  11.  
  12. sub(5)
  13. print ("\nFunction\n=================")
  14. print locals()
  15. print locals()["x"]
  16. print globals()["x"]
  17.  
  18. print ("\nGlobals\n=================")
  19. print globals()
  20.  
  21. fun(2)
  22.  
  23. ///scope.py
  24.  
  25. Globals
  26. =================
  27. {'x': 1,
  28. '__file__':
  29. 'C:\\books\\python\\CH1\\code\\scope.py',
  30. 'fun': <function fun at 0x008D7570>,
  31. 't': <class '__main__.t'>,
  32. 'time': <module 'time' (built-in)>,. . .}
  33.  
  34. Nested Function
  35. =================
  36. {'c': 5, 'b': 3, 'd': 3}
  37.  
  38. Function
  39. =================
  40. {'a': 2, 'x': 4, 'b': 3, 'sub':
  41. <function sub at 0x008D75F0>}
  42. 4
  43. 7

Report this snippet  

You need to login to post a comment.