A
Alex Gittens
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:
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)
return totallen
def cutbits():
cutbit = []
for i in range(0, len(fields)):
if len(fields) >= widths:
cutbit.append(fields[:widths])
fields = fields[widths:]
elif len(fields) > 0:
leftover = widths - len(fields)
if align == 'r':
cutbit.append(' '*leftover + fields)
elif align == 'l':
cutbit.append(fields + ' '*leftover)
else:
raise 'Unsupported alignment option'
fields = ''
else:
cutbit.append(' '*widths)
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
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:
Traceback (most recent call last):fieldprint([5, 4], 'rl', ['Ae', 'Lau'])
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)
return totallen
def cutbits():
cutbit = []
for i in range(0, len(fields)):
if len(fields) >= widths:
cutbit.append(fields[:widths])
fields = fields[widths:]
elif len(fields) > 0:
leftover = widths - len(fields)
if align == 'r':
cutbit.append(' '*leftover + fields)
elif align == 'l':
cutbit.append(fields + ' '*leftover)
else:
raise 'Unsupported alignment option'
fields = ''
else:
cutbit.append(' '*widths)
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