Testing validity of for...in...

Gonçalo Rodrigues op73418 at mail.telepac.pt
Mon Nov 3 07:35:41 EST 2003


On Mon, 03 Nov 2003 12:53:18 +0100, Richard Philips
<richard.philips at ua.ac.be> wrote:

>Hi,
>
> From the "The Pragmatic Programmer / Dave Thomas, Andy Hunt",
>I acquired the habit to insert assertions in function declarations:
>
>def maxlength(mylist):
>    assert isinstance(mylist, list), "A list with strings"
>    max = -1
>    for item in list:
>        if len(item)>max:
>           max = len(item)
>    return max
>
>
>But if you look at the code, maxlength is meaningful if mylist supports 
>the "for ... in ...".
>

The following should work:

try:
    it = iter(mylist)
except TypeError:
    raise TypeError("Object not iterable.", mylist)

Except I'm wondering what you would be gaining, besides the marginally
better error description, by putting this check in. TypeError will be
raised anyway by the time you get to the for loop, so, IMHO, it's just
better to document your function:

def maxlength(mylist):
    """...
    Warning(s):
    - Raises TypeError if argument is not iterable.
    """
    max = -1
    for item in list:
        if len(item)>max:
           max = len(item)
    return max

With my best regards,
G. Rodrigues




More information about the Python-list mailing list