0

python 3.7

>>> exec('foobz = 3')
>>> print(foobz)
3

why does the above work but the below does not?

>>> 
def blah():
    exec('foobz = 3')
    print(foobz)
>>> ... ... ... 
>>> blah()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in blah
NameError: name 'foobz' is not defined

I've verified that its not due to spacing and I'm unclear what the difference is

George Mauer
  • 117,483
  • 131
  • 382
  • 612

1 Answers1

1

This question was answered here, but tl;dr the exec statement follows different rules when it comes to scope and lifecycle in your application:

https://stackoverflow.com/a/45535337/6670005

FelizNaveedad
  • 358
  • 2
  • 7