What Does Python vars() Return Without Arguments?

In Python, calling the built-in vars() function without any arguments returns a dictionary representing the current local symbol table, behaving identically to the locals() function. This article explains the exact behavior of vars() when called with no parameters, how its output depends on the context in which it is executed, and an important caveat regarding modifying its returned dictionary.

Default Behavior: Equivalent to locals()

When you invoke vars() without passing an object, Python's runtime redirects the call to locals(). The official Python specification states:

"Without an argument, vars() acts like locals()."

The contents of this dictionary vary depending on whether the call takes place at the module level, inside a function, or within a class body.

At the Module Level

At the top level of a module or script, the local namespace is identical to the global namespace. Consequently, calling vars() without arguments in a module-level context returns the module's global dictionary, which matches the output of globals().

# module_example.py
x = 10
y = "hello"

# At the module level, vars() returns the global symbol table
module_vars = vars()
print(module_vars["x"])  # Output: 10
print(module_vars["y"])  # Output: hello

The returned dictionary includes standard module-level attributes such as __name__, __doc__, __file__, and any user-defined variables or imported modules.

Inside a Function

When invoked inside a function or method, vars() captures only the local variables, parameters, and bindings defined in that function's current frame up to the point of the call.

def calculate_area(length, width):
    area = length * width
    current_scope = vars()
    return current_scope

result = calculate_area(5, 10)
print(result)
# Output: {'length': 5, 'width': 10, 'area': 50}

The resulting dictionary contains keys for each local identifier and values corresponding to the objects bound to them.

Important Limitation: Mutation Caveat

While vars() returns a dictionary, attempting to modify this dictionary inside a function does not guarantee changes to the actual local variables.

Python optimizes local variable access at compile time using arrays of values (accessed via the LOAD_FAST bytecode instruction) rather than querying a dictionary dynamically. Therefore, updates made to the dictionary returned by vars() inside a function are typically ignored by the interpreter and will not update the local variable bindings. At the module level, however, modifying the dictionary directly alters the module's global namespace because module globals are stored in an actual dictionary.