Recurring patterns: Am I missing it, or can we get these added to the language?

Jeffrey Froman jeffrey at fro.man
Tue Apr 15 17:01:07 EDT 2008


Erich wrote:
> def iterable(item, count_str=False):
>     if not count_str and isinstance(item, str):
>         return False
>     try:
>         iter(item)
>     except:
>         return False
>     return True

Beware the "except" clause here, as it catches *all* errors. Thus, if you
happen to have an unfortunate typo:

        try:
            iter(iten)
        except:
            return False
        return True


then your code will happily return False for everything. This code should
catch TypeErrors only for better results:

        try:
            iter(item)
        except TypeError:
            return False
        return True



Jeffrey



More information about the Python-list mailing list