Re: why UnboundLocalError?
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: why UnboundLocalError?

From: Peter Hansen <peter@engcorp.com>
Date: Sat Jul 09 2005 - 04:29:28 CEST

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
Received on Thu Sep 29 16:50:39 2005