[Tutor] Newbie problem with TypeError

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Nov 17 13:30:02 EST 2003

On Mon, 17 Nov 2003, Jonathan Soons wrote:

> def mklines(field) :
>     if len(field) < 4 :
>         return
>     words = field.split(" ")
>     while len(words) > 1 :
>         line = ""
          list(words)                   #definitely a list

Hi Jonathan,

That line that's I've underlined is one possible problem.  It asks Python
to compute the list of words.  But it does not rebind 'words' to that list

>>> s = 'hello'
>>> list(s)
['h', 'e', 'l', 'l', 'o']
>>> s

So list(s) does not mutate 's' itself.  If we want to capture the value of
list(s), we can bind it with an assignment:

    s = list(s)

The same bug occurs later in the code with str():

>             str(words)           #newpage() requires string argument

Anyway, the block of code:

>         if PDF_get_value(pdf, "texty", 0) < INCH :
>             words = string.joinfields(words, " ")
>             str(words)                #newpage() requires string argument
>             newpage(words)

looks very suspicious.

Why is this rebinding the name 'words' to a string?  Once we come out of
the if statement, 'words' doesn't revert back to a list, so this is most
likely the location where the TypeError arises.

Try to avoid rebinding variables to different types.  Doing so is tempting
--- it feels like we're saving variable names.  But it's problematic,
since it makes it less simple to figure out what's going on with the

We can avoid the problem by not rebinding to 'words'.  Instead of:

if PDF_get_value(pdf, "texty", 0) < INCH :
    words = string.joinfields(words, " ")

we can say:

if PDF_get_value(pdf, "texty", 0) < INCH :
    newpage(string.joinfields(words, " "))

Please feel free to ask questions about this on Python-Tutor.  Good luck!

More information about the Tutor mailing list