Home >Backend Development >Python Tutorial >How Do globals(), locals(), and vars() Differ in Python?

How Do globals(), locals(), and vars() Differ in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 02:16:03396browse

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.

  • Within a Function: locals() returns a dictionary of the function's namespace. It includes local variables as well as closure variables at the time of the call. Updates to the dictionary are reflected in the local variables. However, assignments to the returned dictionary do not modify the local variables.

For example, in a function:

def example():
    x = 1
    l = locals()
    l['x'] = 3
    print(x)  # Outputs 1, not 3
  • Outside a Function: locals() returns the actual namespace dictionary. Changes made to the dictionary are reflected in the namespace, and vice versa.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn