why UnboundLocalError?
Alex Gittens
swiftset at gmail.com
Fri Jul 8 22:21:36 EDT 2005
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):
def measure():
totallen = 0
for i in range(0, len(fields)):
totallen += len(fields[i])
return totallen
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]:]
elif len(fields[i]) > 0:
leftover = widths[i] - len(fields[i])
if align[i] == 'r':
cutbit.append(' '*leftover + fields[i])
elif align[i] == 'l':
cutbit.append(fields[i] + ' '*leftover)
else:
raise 'Unsupported alignment option'
fields[i] = ''
else:
cutbit.append(' '*widths[i])
return cutbit.join('')
if len(widths) != len(fields) or len(widths)!=len(align) or
len(align)!=len(fields):
raise 'Argument mismatch'
str = ''
while measure()!=0:
str += cutbits()
What's causing the error?
Thanks,
Alex
--
ChapterZero: http://tangentspace.net/cz/
More information about the Python-list
mailing list