[Python-ideas] __iter__ implies __contains__?
Steven D'Aprano
steve at pearwood.info
Sun Oct 2 16:10:33 CEST 2011
Antoine Pitrou wrote:
> On Sat, 1 Oct 2011 22:30:21 -0400
> Nick Coghlan <ncoghlan at gmail.com> wrote:
>> On Sat, Oct 1, 2011 at 9:21 PM, Chris Rebert <pyideas at rebertia.com> wrote:
>>> Actually, my suggestion was just that Sequence is one possible (but
>>> clean) way to obtain the behavior; one could *of course* reimplement
>>> the functionality without recourse to Sequence if they desired.
>> But why would that would forcing everyone implementation standard
>> sequences to reimplement the wheel be an improvement over the status
>> quo?
>
> You don't reinvent the wheel if you accept to inherit from abc.Sequence.
You shouldn't be forced to inherit from abc.Sequence to implement the
sequence protocols. The whole point of protocols is that they you don't
need inheritance to make them work, let alone buy into the ABC mindset.
If you have a class that you don't want to be iterable but otherwise
obeys the iteration protocol, that is easy to fix: have __iter__ raise
TypeError. An easy fix for unusual and trivial problem.
>>> class Test:
... def __getitem__(self, i):
... return i
... def __iter__(self):
... raise TypeError
...
>>> for i in Test():
... print(i)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __iter__
TypeError
--
Steven
More information about the Python-ideas
mailing list