The locals()
function returns a dictionary containing the mapping between the variables defined in the current local scope and their values.
Syntax:
locals()
copy
The values returned are references meaning that by modifying a value in the dictionary, we effectively modifies the local variable in the current scope.
x = 5 y = 10 locals()['x'] = 50 locals()['y'] = 100 print(locals()) print(x) print(y)
copy
Output:
{'x':50, 'y':100}
50
100
x = 5 y = 10 z =0 locals()['x'] = 50 locals()['y'] = 100 locals()['z'] = 500 print(locals()) print(x) print(y) print(z)
copy
Output:
{'x':50, 'y':100, 'z':500}
50
100
500
The locals()
function is a useful tool for debugging and inspecting the values of variables within a local scope. It is also commonly used in conjunction with the globals() function to update the values of global variables.