Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python nonlocal - why sometimes need it and sometimes not [closed]

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

like image 676
uoay Avatar asked Aug 30 '26 16:08

uoay


1 Answers

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.

like image 174
Tom Karzes Avatar answered Sep 01 '26 06:09

Tom Karzes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!