0

I discovered that on Debian with Python 2.5.5 the collections module does not have Iterable class.

Example: http://python.codepad.org/PxLHuRFx

The same code executed on OS X 10.8 with Python 2.5.6 this works, so I assume that this is missing for some reason.

What workaround do I have to make my code pass this on all Python 2.5+ ?

sorin
  • 161,544
  • 178
  • 535
  • 806
  • 4
    Duplicate of this question: http://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable which has an answer. – phkahler Nov 19 '12 at 17:58

2 Answers2

4

I would check to see if the object has an __iter__ function defined.

So hasattr(myObj, '__iter__')

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
0

This works:

def f(): pass
import sys  
results={'iterable':[],'not iterable':[]}

def isiterable(obj):
    try:
        it=iter(obj)
        return True
    except TypeError:
        return False


for el in ['abcd',[1,2,3],{'a':1,'b':2},(1,2,3),2,f,sys, lambda x: x,set([1,2]),True]:
    if isiterable(el):
        results['iterable'].append('\t{}, a Python {}\n'.format(el,type(el).__name__))
    else:   
        results['not iterable'].append('\t{}, a Python {}\n'.format(el,type(el).__name__))

print 'Interable:'
print ''.join(results['iterable'])

print 'Not Interable:'
print ''.join(results['not iterable'])

Prints:

Interable:
    abcd, a Python str
    [1, 2, 3], a Python list
    {'a': 1, 'b': 2}, a Python dict
    (1, 2, 3), a Python tuple
    set([1, 2]), a Python set

Not Interable:
    2, a Python int
    <function f at 0x100492d70>, a Python function
    <module 'sys' (built-in)>, a Python module
    <function <lambda> at 0x100492b90>, a Python function
    True, a Python bool

This is more fully explored on this SO post.

Community
  • 1
  • 1
the wolf
  • 34,510
  • 13
  • 53
  • 71