0

When I execute the following code in a python shell,

def foo():
  bar = 0
  vars()['bar'] = 1
  print('within function: ' + str(bar))

foo()
baz = 0
vars()['baz'] = 1
print('inline: ' + str(baz))

I get

within function: 0
inline: 1

Why do setting variables via vars() seems to work inline but not when called from within a function?

user209974
  • 1,737
  • 2
  • 15
  • 31
  • Without an argument, `vars` within a function is the same as `locals`, and at the top-level is the same as `globals`. For the differences between `locals` and `globals`, see the linked question. – user200783 Feb 22 '19 at 11:08
  • Not exactly a duplicate, but the answers [here](https://stackoverflow.com/q/1450275/1222951) explain what the problem is. – Aran-Fey Feb 22 '19 at 11:12
  • There's also [this](https://stackoverflow.com/questions/30295163/update-locals-from-inside-a-function) actual duplicate, but I don't think its answer is good. – Aran-Fey Feb 22 '19 at 11:12

0 Answers0