Notes

`locals()` Function in Python [ English ]

< Prev Next >

1. Introduction

The locals() function in Python is a built-in function used to return a dictionary containing the current local symbol table. In simple terms, it provides a mapping of all local variables and their values within the current scope.

Local variables are variables that are defined inside a function or a specific block of code. The locals() function allows programmers to inspect these variables and their current values during program execution.

2. Syntax

locals()

Parameters

Return Value

3. Example in Global Scope

a = 10
b = 20

print(locals())

Output (example)

{'a': 10, 'b': 20, '__name__': '__main__', '__builtins__': {...}}

Explanation

4. Example Inside a Function

def display():
    x = 5
    y = 10
    print(locals())

display()

Output

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

Explanation

5. Accessing Local Variables from the Dictionary

The dictionary returned by locals() can be used to access values of local variables.

def example():
    a = 3
    b = 7

    local_vars = locals()
    print(local_vars['a'])
    print(local_vars['b'])

example()

Output

3
7

Explanation

6. Practical Example

def student():
    name = "Rahul"
    age = 20
    course = "BCA"

    print(locals())

student()

Output

{'name': 'Rahul', 'age': 20, 'course': 'BCA'}

Explanation

7. Difference Between locals() and globals()

Feature locals() globals()
Purpose Returns local variables Returns global variables
Scope Current function or block Entire program
Return type Dictionary Dictionary

Example:

x = 100

def test():
    y = 50
    print("Local:", locals())
    print("Global:", globals())

test()

8. Uses of locals()

The locals() function is useful for:

9. Summary

< Prev Next >