[docs] [issue10043] UnboundLocalError with local variable set by setattr, caused by code run later

Eric Smith report at bugs.python.org
Thu Oct 7 14:31:16 CEST 2010

Eric Smith <eric at trueblade.com> added the comment:

It's a well documented behavior.

Surely you ran across this link while researching your problem? http://docs.python.org/reference/executionmodel.html#naming-and-binding
The paragraph beginning "The following constructs bind names ..." describes why setattr does not create a binding, although I'll grant that it doesn't mention setattr by name. The paragraph beginning "If a name binding operation occurs anywhere within a code block ..." explains why the assignment affects code that occurs before the binding.

If you'd like to improve the docs, please suggest a patch.

Also note that you're not creating a local variable with setattr, you're creating a module level (sometimes called global) variable. Perhaps that's part of the misunderstanding? You might want to look into the global (on nonlocal) statement, unless there's some particular reason the name you're creating needs to be dynamically computed.

assignee:  -> docs at python
components: +Documentation -Interpreter Core
nosy: +docs at python
resolution: invalid -> 
stage:  -> needs patch
status: closed -> open
versions: +Python 3.2 -Python 2.6

Python tracker <report at bugs.python.org>

More information about the docs mailing list