0

NOTE: Please read the full question before tagging this as a duplicate of Accessing variables defined in enclosing scope.

Why is it possible to use a nonlocal dict but not a scalar value within a closure in python? For example:

def something():
    SCALAR = 0
    DICT = {0:0}
    def _inner():
        SCALAR += 1 # no
        DICT[0] += 1 # yes
samuelbrody1249
  • 3,459
  • 1
  • 7
  • 31
  • 1
    I said that you could edit the other question to explain what's the difference. – user202729 Feb 22 '21 at 03:16
  • 1
    Besides "NOTE: please read the full question" won't end well. Explaining is properly like you did https://stackoverflow.com/questions/66309513/python-global-vs-dict#comment117229297_66309513 is better. – user202729 Feb 22 '21 at 03:18
  • 1
    To complete your example (i.e. show the error), you need to call to _inner inside function something. – DarrylG Feb 22 '21 at 03:23
  • 2
    Short explanation: because `x += y` involves an *assignment* to the variable `x`, hence marking that `x` as *local*. On the other hand, `x[i] += y` *does not involve an assignment to `x`* The **types** of the object being referred to *are completely irrelevant*. For example, try `x = [0]` and then in `_inner`, `x[0] += 1` will work, but `x += [1]` will fail – juanpa.arrivillaga Feb 22 '21 at 03:26
  • @juanpa.arrivillaga Re the duplicate: OP's issue in this case is that they want an explanation on why the dict assignment **works**. (I can find some for global, see the other post) – user202729 Feb 22 '21 at 03:50

0 Answers0