[Python-3000] Thoughts on collections.Container and collections.Iterable

Raymond Hettinger python at rcn.com
Sat Feb 9 02:35:57 CET 2008


I'm wondering if collections.Iterable should inherit from collections.Container"?

In Python, anything that supports __iter__ automatically supports tests using the "in" operator:

   class A:
       def __iter__(self):
           for i in (1,2,3):
                yield i
   >>> 2 in A()
   True

The two concepts are deeply related.  Anywhere we can write "for x in s: ..." we can also write "if x in s: ...".

The new definition of Iterable would look like this:

    class Iterable(Container):
        __metaclass__ = ABCMeta

        @abstractmethod
        def __iter__(self):
            while False:
                yield None

        @classmethod
        def __subclasshook__(cls, C):
            if cls is Iterable:
                if any("__iter__" in B.__dict__ for B in C.__mro__):
                    return True
            return NotImplemented

        def __contains__(self, value):
            for v in self:
                if v == value:
                    return True
            return False


Raymond


More information about the Python-3000 mailing list