Since Python 2.6, with the introduction of abstract base classes, isinstance
(used on ABCs, not concrete classes) is now considered perfectly acceptable. Specifically:
from abc import ABCMeta, abstractmethod
class NonStringIterable:
__metaclass__ = ABCMeta
@abstractmethod
def __iter__(self):
while False:
yield None
@classmethod
def __subclasshook__(cls, C):
if cls is NonStringIterable:
if any("__iter__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
This is an exact copy (changing only the class name) of Iterable
as defined in _abcoll.py
(an implementation detail of collections.py
)... the reason this works as you wish, while collections.Iterable
doesn't, is that the latter goes the extra mile to ensure strings are considered iterable, by calling Iterable.register(str)
explicitly just after this class
statement.
Of course it's easy to augment subclasshook by returning False
before the any
call for other classes you want to specifically exclude from your definition.
In any case, after you have imported this new module as myiter
, isinstance('ciao', myiter.NonStringIterable)
will be False
, and isinstance([1,2,3], myiter.NonStringIterable)
will be True
, just as you request -- and in Python 2.6 and later this is considered the proper way to embody such checks... define an abstract base class and check isinstance
on it.