[docs] [issue10043] UnboundLocalError with local variable set by setattr, caused by code run later
Steven Samuel Cole
report at bugs.python.org
Thu Oct 7 15:03:52 CEST 2010
Steven Samuel Cole <steven.samuel.cole at gmail.com> added the comment:
thank you very much for the clarification.
i did indeed not come across the page you've linked to, mainly because i did not really know what to google for. actually, i do not recall ever looking into the python language reference in 6+ years of python coding.
googling for 'python UnboundLocalError setattr' returns this bug report as top result at the moment, as your link leads to more indepth information, the main objective of saving / alleviating others the research work seems achieved. i will nonetheless try to make time to get get my head around the python doc conventions and processes and submit a patch.
thanks for pointing out the difference between a local variable and one with module scope. however, it is not relevant for my situation: i have a long list of strings coming in (database column names, not under my influence) which i need to access _like_ a local variable. if you can think of a smarter approach to turn parameter strings into variables of whatever scope, i'm all ears, but i have a feeling that's actually what setattr(...) is meant for.
as a quick fix for the UnboundLocalError, sticking to working with module attributes worked for me. instead of changing the value of a dynamically created variable in the conventional way
my_var = None
(which is where the error occurred in my code), it might help to use setattr(...) even if the variable name is known:
setattr(modules[__name__], 'my_var', None)
Python tracker <report at bugs.python.org>
More information about the docs