is_iterable function.

danmcleran at yahoo.com danmcleran at yahoo.com
Wed Jul 25 20:58:40 CEST 2007


You can use the built-in dir() function to determine whether or not
the __iter__ method exists:

class Iterable(object):
    def __iter__(self):
        pass

class NotIterable(object):
    pass

def is_iterable(thing):
    return '__iter__' in dir(thing)

print 'list is iterable = ', is_iterable(list())
print 'int is iterable = ', is_iterable(10)
print 'float is iterable = ', is_iterable(1.2)
print 'dict is iterable = ', is_iterable(dict())
print 'Iterable is iterable = ', is_iterable(Iterable())
print 'NotIterable is iterable = ', is_iterable(NotIterable())

Results:
list is iterable =  True
int is iterable =  False
float is iterable =  False
dict is iterable =  True
Iterable is iterable =  True
NotIterable is iterable =  False

On Jul 25, 12:24 pm, Neil Cerutti <horp... at yahoo.com> wrote:
> def is_iterable(obj):
>     try:
>         iter(obj)
>         return True
>     except TypeError:
>         return False
>
> Is there a better way?
>
> --
> Neil Cerutti





More information about the Python-list mailing list