如何在所有平台上测试一个对象是否可以在python 2.5+上迭代?

时间:2012-11-19 17:56:00

标签: python collections python-2.5 iterable

我发现在使用Python 2.5.5的Debian上,collections模块没有Iterable类。

示例:http://python.codepad.org/PxLHuRFx

在OS X 10.8上使用Python 2.5.6执行相同的代码,这是有效的,所以我认为由于某种原因这是缺失的。

我需要有什么解决方法让我的代码在所有Python 2.5+上传递?

2 个答案:

答案 0 :(得分:4)

我会检查对象是否定义了__iter__函数。

所以hasattr(myObj, '__iter__')

答案 1 :(得分:0)

这有效:

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'])

打印:

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 SO post上更全面地探讨了这一点。