Testing validity of for...in...

Alex Martelli aleax at aleax.it
Mon Nov 3 13:57:15 CET 2003

Richard Philips wrote:

>  From the "The Pragmatic Programmer / Dave Thomas, Andy Hunt",
> I acquired the habit to insert assertions in function declarations:

Actually, I doubt Thomas & Hunt do "type assertions" when they
program in their favourite language, Ruby (whose dynamic but strong
typing is quite similar to Python's).

> def maxlength(mylist):
>     assert isinstance(mylist, list), "A list with strings"

But as you notice, this will refuse arguments that would work
perfectly well, e.g. a _tuple_ of strings, and not trigger for
arguments whose type is not ok, e.g. a list one of whose item
is for example an int.  So what use is it...?!

>     max = -1
>     for item in list:

Hopefully you mean "in mylist".

>         if len(item)>max:
>            max = len(item)
>     return max

...and the whole function is best coded as:

   return max([ len(item) for item in mylist ])

> But if you look at the code, maxlength is meaningful if mylist supports
> the "for ... in ...".

...AND each item supports len().  Yep, very different from what the
assertion expresses.

> Is there an easy way to test if "mylist" supports  "for ... in ..." ?

Sure: just omit the assertion and get to the "for item in mylist:"
statement -- IT will raise (a more precise TypeError rather than a
vaguer AssertionError) if mylist is not iterable.  Similarly, when
you try doing len(item) on each item, it will raise a TypeError if
the item does not support having len() called on it.

Generally, in languages with strong but dynamic typing, assertions
on types aren't a great way to proceed.  Most of the time you can
just go ahead and rely on the language raising exceptions for you
as appropriate if the types are not compatible with your code.  In
some rare cases you may want to do earlier checks/diagnostics, in
which case the idioms I suggest in a Cookbook recipe may help -- see
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52291 for
more (it's better developed in the printed version of the Cookbook
published by O'Reilly).


More information about the Python-list mailing list