Python locals(): Access Local Variables Dynamically

The locals() function returns a dictionary of all local variables in the current scope. It’s useful for debugging, dynamically managing function variables, and inspecting variable states inside functions.

Example

def example():
    x = 10
    y = 20
    print(locals())

example()

Output:

{'x': 10, 'y': 20}

The locals() function returns all variables inside the function as a dictionary.

Syntax

locals()
  • Returns → A dictionary of all local variables in the current scope.

1. Getting Local Variables Inside a Function

def test():
    name = "Alice"
    age = 25
    return locals()

print(test())

Output:

{'name': 'Alice', 'age': 25}

Useful for debugging function variables.

2. Modifying Variables Dynamically

You can update local variables by modifying locals(), but changes don’t affect function execution.

def change_vars():
    a = 5
    locals()['a'] = 100
    print(a)  # Output: 5 (change doesn't affect execution)

change_vars()

Python ignores manual changes to locals() inside functions.

3. Using locals() in a Class Method

class Person:
    def __init__(self, name, age):
        self.data = locals()  # Captures all local variables

p = Person("Bob", 30)
print(p.data)

Output:

{'self': <__main__.Person object>, 'name': 'Bob', 'age': 30}

This captures constructor arguments dynamically.

4. Checking Local Variables in Global Scope

x = 100
print(locals())

Returns all global variables if used outside a function.

Key Notes

  • Returns a dictionary of local variables in a function.
  • Can be used for debugging and variable inspection.
  • Changes to locals() inside functions don’t affect execution.
  • Works in class methods, functions, and global scope.

By using locals(), you can inspect function variables dynamically, making debugging and variable handling easier and more flexible. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top