0

I have found a similar question Python variable scope error. It's related to immutable variable. But when I test mutable variable, I don't know how Python interpreter decides the scope of the variable.

Here's my sample code:

def test_immutable():
    a = 1
    b = 2

    def _test():
        print(a)
        print(b)

        a += 1
        print(a)

    _test()

def test_mutable():
    _dict = {}

    def _test():
        print(_test.__dict__)

        _dict['name'] = 'flyer'

         print('in _test: {0}'.format(_dict['name']))

    _test()

    print(_dict['name'])


if __name__ == '__main__':
    # test_immutable()    # throw exception
    test_mutable()    # it's ok
Community
  • 1
  • 1
flyer
  • 9,280
  • 11
  • 46
  • 62
  • 1
    Your question is identical to the one you linked. In one case you are assigning the variable, in the other case you are *referencing* it. – Bakuriu Jul 23 '14 at 07:34

1 Answers1

2

Immutable vs mutable has nothing to do with variable scoping. Variables are just names, and always work the same way. Scoping is even decided at compile time, long before Python knows what you're going to assign to them.

The difference between your two functions is that the first one assigns directly to a with the += operator, which causes a to become a local. The second one assigns to a key inside _dict, which ultimately calls a method on the dict object, and doesn't affect the variable's scoping.

Eevee
  • 47,412
  • 11
  • 95
  • 127