Home >Backend Development >Python Tutorial >How Do globals(), locals(), and vars() Differ in Python?
Exploring the Nuances of globals(), locals(), and vars()
Python offers three introspection functions that provide insights into the current namespace: globals(), locals(), and vars(). Each returns a dictionary with specific information.
globals()
globals() consistently returns the dictionary of the current module's namespace. It provides access to all globally defined names within the module.
locals()
locals() is dynamic and its behavior depends on the scope.
For example, in a function:
def example(): x = 1 l = locals() l['x'] = 3 print(x) # Outputs 1, not 3
For instance:
class Test: a = 'one' huh = locals() b = 'two' huh['c'] = 'three' print(huh) # Outputs {'a': 'one', 'b': 'two', 'c': 'three', 'huh': {...}}
vars()
vars() accepts an object as its argument and returns its dict attribute. Typically, an object's dict stores its attribute data. Therefore, supplying an object to vars() provides access to its attributes.
class Test: a = 'one' b = 'two' huh = vars(self) c = 'three' huh['d'] = 'four'
In this example, vars(self) returns the dict attribute of the Test instance, allowing access to its attributes like 'a', 'b', and 'c'.
The above is the detailed content of How Do globals(), locals(), and vars() Differ in Python?. For more information, please follow other related articles on the PHP Chinese website!