python nonlocal - why sometimes need it and sometimes not

985 views Asked by At

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

1

There are 1 answers

0
Tom Karzes On

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.