-2

i am using globals() and locals() to view the variables in the global and local space. however i am able to add variables to the global space using globals() but not able to add local variables using locals().

x=10
def show():
    y=20
    locals()['k']=40
    print(locals()['k'])
    print("k=",k)# generates error
    

show()
print(globals())
globals()['newkey']=77
print(globals())
print("newkey=",newkey)# shows error in editor typing but runs properly

how can we add local variable using locals

user2779311
  • 1,688
  • 4
  • 23
  • 31

1 Answers1

1

Using locals/globals dictionary initialization you split the initialization as a key pair, a string with the variable identifier and its value. So each time the you need the value you have to deal with a string as a dictionary key or a string to be evaluated.

def a():
    locals()['k'] = 40
    print('k' in locals())

    print(f"k={locals()['k']}") # dict-way

    print(f"k={eval('k')}") # eval-way

Output

True # so it is in the name space!
k=40
k=40

Remark: if you try to call the variable directly k the compiler will complain raising a NameError: name 'k' is not defined exception.

cards
  • 3,936
  • 1
  • 7
  • 25