why UnboundLocalError?

and-google at doxdesk.com and-google at doxdesk.com
Sat Jul 9 08:26:46 EDT 2005


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]]

-- 
Andrew Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/




More information about the Python-list mailing list