why UnboundLocalError?

Peter Hansen peter at engcorp.com
Fri Jul 8 22:29:28 EDT 2005


Alex Gittens wrote:
> I'm trying to define a function that prints fields of given widths
> with specified alignments; to do so, I wrote some helper functions
> nested inside of the print function itself. I'm getting an
> UnboundLocalError, and after reading the Naming and binding section in
> the Python docs, I don't see why.
> 
> Here's the error:
> 
>>>>fieldprint([5, 4], 'rl', ['Ae', 'Lau'])
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "fieldprint.py", line 35, in fieldprint
>     str += cutbits()
>   File "fieldprint.py", line 11, in cutbits
>     for i in range(0, len(fields)):
> UnboundLocalError: local variable 'fields' referenced before assignment
> 
> This is the code:
> def fieldprint(widths,align,fields):
> [snip]
>         def cutbits():
>                 cutbit = []
>                 for i in range(0, len(fields)):
>                         if len(fields[i]) >= widths[i]:
>                                 cutbit.append(fields[i][:widths[i]])
>                                 fields = fields[widths[i]:]
> 
> What's causing the error?

While I don't know the "correct" fix, the immediate cause is that you 
are assigning to "fields" in the final line above, and there is no 
"global fields" statement, so the compiler thinks it must be a local, 
but you access it (as the error says) before it is assigned-to locally.

"A" fix would be to use a different name locally, and if you really want 
it to reference the externally defined "fields", just do something like 
"lfields = fields" at the top of cutbits()  (where "lfields" means 
"local fields", though you can pick any name you like).

-Peter



More information about the Python-list mailing list