Home >Backend Development >Python Tutorial >What's the Difference Between `globals()`, `locals()`, and `vars()` in Python?

What's the Difference Between `globals()`, `locals()`, and `vars()` in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 20:22:02746browse

What's the Difference Between `globals()`, `locals()`, and `vars()` in Python?

Understanding the Differences Between globals(), locals(), and vars()

In Python, globals(), locals(), and vars() are functions that provide insights into the current program's namespace. Let's explore their distinctions:

globals()

  • Purpose: Returns a dictionary of the global namespace.
  • Behavior: Consistent, always returning the namespace dictionary for the current module.

locals()

  • Purpose: Acquires a dictionary representing the current namespace.
  • Behavior: Dynamic, depending on the caller's context.
  • Inside a function: Returns a dictionary containing the current local variables and any closure variables. Multiple calls within the same stack frame return the same dictionary due to its association with the frame object's f_locals attribute. Updates to this dictionary are reflected in the local namespace, but assigning values directly to the dictionary does not modify the corresponding local variables.
  • Outside a function: Returns the actual dictionary that serves as the current namespace. Changes to this dictionary are synchronized with the namespace, and vice versa.

vars()

  • Purpose: Accepts an object as an argument and returns the dict attribute of that object.
  • Behavior:

    • With no argument, it returns the dict of the current namespace (similar to locals() outside a function).
    • When provided an object, it retrieves the object's __dict__, typically containing its attribute data.
    • Updates to the returned dictionary influence the object's attributes, and conversely, changes to the object's attributes are reflected in the dictionary.

Key Note:

The behavior of locals() and vars() may vary across Python versions and implementations. In CPython 2.x, locals() could work differently with the use of "exec 'pass'".

The above is the detailed content of What's the Difference Between `globals()`, `locals()`, and `vars()` 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