6

Python scope I have the same question but slightly different.

number = 0
def incrementNumber():
    number += 1

This one above does not work but this one below does why? Both are outside the function scope.

number = {'num':0}
def incrementNumber():
    number['num'] += 1

First one works if I add the variable as global

number = 0
def incrementNumber():
    global number
    number += 1
Community
  • 1
  • 1
Andreas
  • 989
  • 1
  • 8
  • 10

2 Answers2

4

Check out this blog post, it's similar to what you're doing. Specifically adam's comment.

You don't assign to dictionaryVar, you assign to dictionaryVar['A']. So it's never being assigned to, so it's implicitly global. If you were to actually assign to dictionaryVar, you'd get the behavior you were "expecting".

John
  • 13,197
  • 7
  • 51
  • 101
  • What does the "it's" refer to in the second sentence, the dictionaryVar or the dictionaryVar['A']? It seems like the dictionaryVar['A'], so is "adam" saying that dictionaryVar['A'] is implicitly global? Why is that the case. I would expect, like the blogger, that dictionaryVar['A'] wouldn't be implicitly global if dictionaryVar wasn't... Can you explain a little more in your answer? – hft Dec 19 '17 at 17:44
0

In the first case int is not mutable, so when you do number +=1 your are really updating where number points. As you, in general, do not want changes to propagate up-scope with out explicitly telling it to, python does a copy-on-write and gives you a local variable number. You than increment that variable and it is thrown away when the function returns

In the case of dictionaries, which are mutable, you are grabbing the up-scope reference and then mutating the underlying object, thus your addition propagates out of the function.

In the last case you have explicitly told python to not make number a local variable, thus the changes propagate out as you want.

related python closure local variables

Community
  • 1
  • 1
tacaswell
  • 84,579
  • 22
  • 210
  • 199