2 ms·
Shadowing in Python gave me an UnboundLocalError
- mont_tag 2y agoInterestingly, I encountered exactly this issue this week. It was mystifying for a short while but easily hunted down. Perhaps lint tools would have been of help.
- zahlman 2y agoYes, a very common problem. There are now hundreds of duplicates on Stack Overflow closed to https://stackoverflow.com/questions/370357 https://stackoverflow.com/questions/370357 (I did a lot of this work, along with editing the cross-references into the question and contributing my own detailed answer).
- compressedgas 2y agoThe problem with Python is that it lacks a binding operator. So any assignment to something causes that name to be bound in the local scope unless the name has been declared global or nonlocal. In Scheme this kind of error never occurs because Scheme has binding operators which are used much more than the assignment operator set!. This error does not occur in Pico either because binding with : always produces a local but assignment with := goes up the nested scopes to find the nearest binding to reassign. The fix in Python is to introduce the required global or nonlocal statement at the start of the function.