<ol>
<li><p>检查<code>__iter__</code>对序列类型有效,但对Python 2中的strings<strong>会失败。我也想知道正确的答案,在那之前,有一种可能性(也适用于字符串):</p>
<pre><code>try:
some_object_iterator = iter(some_object)
except TypeError as te:
print some_object, 'is not iterable'
</code></pre>
<p>内置的<code>iter</code>检查<code>__iter__</code>方法,如果是字符串,则检查<code>__getitem__</code>方法。</p></li>
<li><p>另一种常见的pythonic方法是假设一个iterable,如果它不能在给定的对象上工作,那么它将优雅地失败。Python词汇表:</p>
<blockquote>
<p>Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a <strong>duck</strong> and quacks like a <strong>duck</strong>, it must be a <strong>duck</strong>.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). <strong>Instead, it typically employs the EAFP (Easier to Ask Forgiveness than Permission) style of programming.</strong></p>
<p>...</p>
<pre><code>try:
_ = (e for e in my_object)
except TypeError:
print my_object, 'is not iterable'
</code></pre>
</blockquote></li>
<li><p><a href="http://docs.python.org/library/collections.html#abcs-abstract-base-classes" rel="noreferrer">^{<cd5>}</a>模块提供一些抽象基类,这些基类允许询问类或实例是否提供特定功能,例如:</p>
<pre><code>from collections.abc import Iterable
if isinstance(e, Iterable):
# e is iterable
</code></pre>
<p>但是,这不会检查可通过<code>__getitem__</code>访问的类。</p></li>
</ol>