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
  • 4,379
  • 1
  • 15
  • 58
  • 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
  • 3
    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
  • yes; and the reason the dict assignment works is because it's *not an assignment*, but a modification of the dict. Python recognizes the `x[y] = z` pattern differently from `x = y` in the grammar (it must, in order to be able to reroute to `x.__setitem__(y, z)`; and in so doing, that changes the *compile-time* rule for whether `x` is deemed a local. I edited the duplicate link to something that should be more precise. – Karl Knechtel Sep 09 '22 at 09:32

0 Answers0