is_iterable function.
Jeff McNeil
jeff at jmcneil.net
Wed Jul 25 15:37:45 EDT 2007
That's not going to hold true for generator functions or iterators
that are implemented on sequences without '__iter__.' You might also
want to check for __getitem__. I'm not sure if there's a way to tell
if a function is a generator without actually calling it.
-Jeff
On 7/25/07, danmcleran at yahoo.com <danmcleran at yahoo.com> wrote:
> 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
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list