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+ ?

1

2 Answers 2

4

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

So hasattr(myObj, '__iter__')

Sign up to request clarification or add additional context in comments.

2 Comments

@thewolf: Perhaps a __getitem__ if there isn't an _iter__?
I think the only reliable way is try: / iter(obj) / except: TypeError
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.