0

I'm confused about the behaviour of dictionaries with global function. In the following examples, why does the first case print {'abc':123} but the second {'abc': 456}? I am using python 2.7.

first example:

def foo():
  test_dict = {}
  bar()

def bar():
    test_dict['abc'] = 123


test_dict = {'abc':456}
foo()
print test_dict

second example:

test_dict = {'abc':456}

def foo():
  test_dict = {}
  test_dict['abc'] = 123
foo()
print test_dict
oli5679
  • 1,709
  • 1
  • 22
  • 34
  • 1
    `bar` does not share a scope with `foo` in your first example. `test_dict` is local to `foo` *only*. Python does not have dynamic scoping (e.g. it doesn't matter where `bar()` was invoked from, only where `bar` is defined). – Martijn Pieters Jan 04 '17 at 17:25
  • 1
    You didn't explain what you expected to happen *instead*, so I'd have normally closed this as *unclear*. I duped you to the canonical post on Python's scoping rules instead. – Martijn Pieters Jan 04 '17 at 17:27

0 Answers0