Python locals() Built in Function
The locals() function in Python returns a dictionary containing the current local symbol table. A symbol table contains necessary information about the current program, such as variable names and values. The locals() function can be used to access or modify local variables inside a function or a class.
Here are some examples of using locals() function in Python:
Using locals() function in Python
# This example prints the local symbol table of the global scope
x = 10
y = 20
print(locals())
# Output: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000021E9F8A7D30>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 10, 'y': 20}
Using Python locals() function inside local scope
# This example prints the local symbol table of a function
def foo():
a = 1
b = 2
print(locals())
foo()
# Output: {'a': 1, 'b': 2}
Updating dictionary values by Python locals() Function
# This example modifies the value of a local variable using locals()
def bar():
c = 3
d = 4
print(c) # Output: 3
locals()['c'] = 5 # Change the value of c to 5 using locals()
print(c) # Output: 5
bar()
Python locals() function for global environment
# This example shows that locals() and globals() return the same dictionary in the global scope
e = 6
f = 7
print(locals() is globals()) # Output: True
Using locals() function inside a class
# This example shows how to use locals() to return the variables and methods of a class
class Test:
def __init__(self):
self.g = 8
self.h = 9
def show(self):
print(locals())
t = Test()
t.show()
# Output: {'self': <__main__.Test object at 0x0000021E9F8B6C70>, 'g': 8, 'h': 9}
Using locals() with list comprehension
# This example shows how to use locals() with list comprehension to filter out variables starting with '_'
i = "Hello"
j = "World"
k = [key for key in locals().keys() if not key.startswith('_')]
print(k)
# Output: ['i', 'j']
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment