locals()
locals() returns a dictionary of symbol table in local name space
global() is same as using locals() in global name space ( or module level )
print(locals())
This will return a dictionary, some sample elements are shown here.
{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None ........
.........}
We can print any element by using key
my_var='plus2net'
print(locals()['my_var']) # plus2net
locals() within a class
class student_kit():
college_name='ABC College' #class attributes
#instance attributes
def __init__(self,name,section):
self.name= name
self.section=section
self.height=5 #instance attribute
print(locals())
Alex=student_kit('Alex','A')
Output is here
{'self': <__main__.student_kit object at 0x000002A8DD23B5F8>,
'name': 'Alex', 'section': 'A'}
Using User defined function
def student_kit():
my_var='plus2net'
print(locals()['my_var']) # plus2net
locals()['my_var']='Welcome'
print(my_var) # plus2net
student_kit()
Output
plus2net
plus2net
Note that the value of variable my_var is not changed.
«All Built in Functions in Python
globals()
dir() ord()
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com