0
def beat():
    exec('nDns=1', locals())
    print(nDns)

beat()

Result NameError: name 'nDns' is not defined. When I change locals() to globals() it works, but I don't really want it written to globals. It must stay in scope of the function. How?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
trshmanx
  • 600
  • 7
  • 16
  • Short version: `locals()` returns a *view* of the existing locals (actually in an array in CPython), but you can't *create/modify* locals by modifying it (because local variables are determined statically when the function is compiled, and it can't detect arbitrary assignments to `dict`s, `eval` or `exec` based additions to locals). [Per the `locals` docs](https://docs.python.org/3/library/functions.html#locals): "Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter. " – ShadowRanger Oct 31 '20 at 14:46
  • @ShadowRanger So what is the solution? – trshmanx Oct 31 '20 at 14:54
  • The duplicate offers options. But frankly, there is no way to *truly* dynamically assign to a local, and thinking you need to do so indicates [an XY problem](https://meta.stackexchange.com/q/66377/322040); you need to find a different design. – ShadowRanger Oct 31 '20 at 15:00

0 Answers0