[Python-ideas] __iter__ implies __contains__?
Nick Coghlan
ncoghlan at gmail.com
Sun Oct 2 16:55:40 CEST 2011
On Sun, Oct 2, 2011 at 10:36 AM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> Again, nobody said you had to inherit from abc.Sequence. It just
> provides a convenience. If you prefer to implement everything by hand,
> then fine. You already have __reversed__(), index() and count() to
> write, so I'm not sure why __contains__() would be scary or annoying.
The case can be made that index() and count() should be based on a
len() style protocol rather than methods (for the same reasons that
len() is a protocol rather than a direct method call).
As for __reversed__, once again, it's optional and not needed for
standard sequences that provide __len__ and an index based
__getitem__:
>>> class MySeq:
... def __len__(self):
... return 10
... def __getitem__(self, index):
... if 0 <= index < 10:
... return index
... raise IndexError(index)
...
>>> seq = MySeq()
>>> len(seq)
10
>>> list(seq)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(reversed(seq))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
It's a judgement call as to how complex an interface can be before we
decide what should be protocol based, what should be optional ABC
based and what should require a specific concrete class.
Strings are really the only class still in the last category. Several
parts of the interpreter used to require real dictionaries, but those
have been slowly culled over the years.
Files are complex enough that an ABC hierarchy makes sense, but even
there, many operations are defined that will accept anything
implementing "enough" of the relevant IO methods rather than
*requiring* that they be explicitly registered with the ABCs.
Collections, however, are fundamental enough that they should ideally
be fully protocol based. The ABCs exist to formalise the APIs, but we
shouldn't be taking fallbacks out of the rest of the interpreter just
because we have shiny new hammer to play with (in fact, the fear of
that happening was one of the major objections to the introduction of
a formal notion of ABCs in the first place).
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list