-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

2
  • 6
    Perhaps this can help: https://stackoverflow.com/a/8028772/8089674 Commented Sep 5, 2021 at 9:15
  • technically you add it but you cannot retrieve its value in that way... Commented Sep 5, 2021 at 10:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.