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.
locals()
Parameters
locals() function does not take any parameters.Return Value
a = 10
b = 20
print(locals())
Output (example)
{'a': 10, 'b': 20, '__name__': '__main__', '__builtins__': {...}}
Explanation
a and b are defined in the current scope, they appear in the dictionary returned by locals().def display():
x = 5
y = 10
print(locals())
display()
Output
{'x': 5, 'y': 10}
Explanation
x and y are local to the function display().locals() returns a dictionary showing these variables and their values.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
locals() returns a dictionary stored in local_vars.a and b are accessed using dictionary keys.def student():
name = "Rahul"
age = 20
course = "BCA"
print(locals())
student()
Output
{'name': 'Rahul', 'age': 20, 'course': 'BCA'}
Explanation
name, age, and course.locals() returns them as key-value pairs in a dictionary.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()
locals()The locals() function is useful for:
locals() is a built-in Python function.