It's always eluded me as to why python has callable(obj) -> bool
but not iterable(obj) -> bool
...
surely it's easier to do hasattr(obj,'__call__')
even if it is slower.
Since just about every other answer recommends using try
/except TypeError
, where testing for exceptions is generally considered bad practice among any language, here's an implementation of iterable(obj) -> bool
I've grown more fond of and use often:
For python 2's sake, I'll use a lambda just for that extra performance boost...
(in python 3 it doesn't matter what you use for defining the function, def
has roughly the same speed as lambda
)
iterable = lambda obj: hasattr(obj,'__iter__') or hasattr(obj,'__getitem__')
Note that this function executes faster for objects with __iter__
since it doesn't test for __getitem__
.
Most iterable objects should rely on __iter__
where special-case objects fall back to __getitem__
, though either is required for an object to be iterable.
(and since this is standard, it affects C objects as well)