0

Related to this question but slightly different.

How can I do R's assign() inside a function?

I tried locals()['x'] = 3 but failed. I tried exec('x=3') but also failed.

How can I access a function's namespace and modify it when I only have string variable that contains the variable name.

on eshirvana's request, I put down the result of exec() inside a function

def f():
    exec('a=3')
    print(a)

f()
# NameError                                 Traceback (most recent # call last)
# Input In [64], in <module>
# ----> 1 f()
#
# Input In [63], in f()
#       1 def f():
#       2     exec('a=3')
# ----> 3     print(a)
# 
# NameError: name 'a' is not defined
KH Kim
  • 1,155
  • 1
  • 7
  • 14
  • why exec() failed? explain better and with detail – eshirvana Feb 26 '22 at 02:38
  • 1
    You cannot dynamically create local variables in CPython, at least, there is no interface to do that (there is nothing except your imagination preventing you from trying various hacks). That is ok, because there is **never a good reason to**. Just use a `dict` or some *other container*. Dynamically creating variables is almost always a bad idea. – juanpa.arrivillaga Feb 26 '22 at 03:38

0 Answers0