2

I know why we need to declare nonlocal in Python and am a bit confused about the following example. Without nonlocal records in line 276, records in line 277 is not defined. However, records in line 289 can be used without any error. without nonlocal

And the following is the situation with nonlocal and it works well. with nonlocal

uoay
  • 306
  • 2
  • 13
  • 3
    Please don't post pictures of your code. See https://meta.stackoverflow.com/q/285551 – khelwood Sep 09 '21 at 14:48
  • usually that's true but this is just a picture that makes the issue immediately obvious. clearly thought was put into using the picture. bruh – Lucas Mumbo Jun 17 '22 at 04:47
  • This should instead be a duplicate of https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use, but it's not worth reopening for that. – Karl Knechtel Sep 10 '22 at 18:34

1 Answers1

9

A nonlocal declaration is analogous to a global declaration. Both are needed only when a function assigns to a variable. Normally, such a variable would be made local to the function. The nonlocal and global declarations cause it to refer to the variable that exists outside of the function.

If a function does not assign to a variable, then the declarations are not needed, and it automatically looks for it in a higher scope.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41