why UnboundLocalError?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Jul 9 00:38:00 EDT 2005


On Fri, 08 Jul 2005 21:21:36 -0500, Alex Gittens wrote:

>         str = ''
>         while measure()!=0:
>                 str += cutbits()

It is considered poor practice to use the names of built-ins like str
or list as variable names.

> What's causing the error?

Did you actually copy all of the code? It seems to me that once your code
has assembled the string, it doesn't actually do anything with it. Not
even return it.

Also, you seem to be calling a join method on lists. Lists don't have join
methods.

The rest of your code is very hard for me to follow, especially as you
have not put any comments in and seem to spend a lot of time re-inventing
the wheel. I would do something like this to handle fixed-width printing.

(Untested.)

def fieldprint(widths,alignments,fields):
    """Given a list of widths, alignments and fields (text) representing
    a single row of text formatted in columns, returns an aligned version.
    Text is never truncated to fit, and is padded with spaces.

    Examples:
    fieldprint([5, 5, 5], "lcr", ["cat", "12345", "12345"])
    => "cat  1234512345"
    fieldprint([5, 5, 5], "rcl", ["cat", "dog", "12345"])
    => "  cat dog 12345"
    fieldprint([5, 5, 5], "rcl", ["cat", "dog", "mice"]) 
    => "  cat dog mice "

    """

    # helper function
    def align(width, alignment, text):
        """Give a width, an alignment, and some text, returns a string
        containing that text aligned correctly in columns.
        """
        if alignment in "Ll":
            # left-justify
            return text.ljust(width)
        elif alignment in "Rr":
            # right-justify
            return text.rjust(width)
        elif alignment in "Cc":
            # centered
            return text.center(width)
        else:
            raise ValueError("Unsupported alignment '%s'" % alignment)

    if not len(widths) == len(alignments) == len(fields):
        raise 'Argument mismatch'
    columns = zip(widths, alignments, fields)
    # builds a list of tuple of (width, alignment, field)
    L = [] # hold each formatted column as it is built
    for column in columns:
        L.append(align(*column))
        # equivalent to:
        # L.append(align(column[0], column[1], column[2]))
    return ''.join(L)


Hope this is helpful to you.


-- 
Steven.




More information about the Python-list mailing list