is_iterable function.

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Jul 22 00:38:30 EDT 2007


Neil Cerutti a écrit :
> def is_iterable(obj):
>     try:
>         iter(obj)
>         return True
>     except TypeError:
>         return False
> 
> Is there a better way?

The only other alternative I see is worse:

def iterable(obj):
   # strings are iterable and don't have an __iter__ method...
   for name in ('__iter__', '__getitem__'):
     try:
       getattr(obj, name)
       return True
     except AttributeError:
       pass
  else:
    return False





More information about the Python-list mailing list