why UnboundLocalError?

Bengt Richter bokr at oz.net
Sat Jul 9 11:10:37 EDT 2005


On 9 Jul 2005 05:26:46 -0700, and-google at doxdesk.com wrote:

>Alex Gittens wrote:
>
>> I'm getting an UnboundLocalError
>
>> def fieldprint(widths,align,fields): [...]
>>     def cutbits(): [...]
>>         fields = fields[widths[i]:]
>
>There's your problem. You are assigning 'fields' a completely new
>value. Python doesn't allow you to rebind a variable from an outer
>scope in an inner scope (except for the special case where you
>explicitly use the 'global' directive, which is no use for the nested
>scopes you are using here).
>
>So when you assign an identifier in a function Python assumes that you
>want that identifier to be a completely new local variable, *not* a
>reference to the variable in the outer scope. By writing 'fields= ...'
>in cutbits you are telling Python that fields is now a local variable
>to cutbits. So when the function is entered, fields is a new variable
>with no value yet, and when you first try to read it without writing to
>it first you'll get an error.
>
>What you probably want to do is keep 'fields' pointing to the same
>list, but just change the contents of the list. So replace the assign
>operation with a slicing one:
>
>  del fields[:widths[i]]

Except the OP probably had two errors in that line, and doesn't want to slice
out fields from the field list, but rather slice characters from the i-th field,
and strings are immutable, so he can't do
   del fields[i][:widths[i]] # slice deletion illegal if fields[i] is a string
and so
   fields[i] = fields[i][:widths[i]]
would be the way to go (see my other post).

Regards,
Bengt Richter



More information about the Python-list mailing list