[Python-Dev] Range __contains__ and objects with __index__ methods
Mark Dickinson
dickinsm at gmail.com
Mon Dec 27 13:44:26 CET 2010
Bah. I meant to send this to the list. (I suspect that Nick also
meant to send his reply to the list.)
On Mon, Dec 27, 2010 at 12:43 PM, Mark Dickinson <dickinsm at gmail.com> wrote:
> On Mon, Dec 27, 2010 at 12:23 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> The symmetry only breaks for a class that breaks the invariant:
>>
>> x == operator.index(x)
>>
>> Failing to guarantee that invariant seems to violate the whole spirit
>> of operator.index().
>
> Agreed. (Though one also needs transitivity, symmetry, etc., of
> equality, since what we really need is that x == y is interchangeable
> with operator.index(x) == y.)
>
>> Perhaps this is what we should be documenting as
>> the true distinguishing feature between the intended semantics of
>> __index__ and the semantics of __int__?
>
> Hmm. Perhaps. For me, this doesn't fully capture the intent of
> __index__, though.
>
> So the semantics (ignoring performance issues for now) would become:
>
> def range_contains(self, x)
> try:
> i = operator.index(x)
> except TypeError:
> i = x
> return any(i == y for y in self)
>
> ?
>
> This change sounds fine to me; it would be good to have a
> documentation note somewhere indicating that the range implementation
> assumes x == index(x), though. This might belong in the range
> documentation, or perhaps the __index__ method documentation could
> indicate that some builtins might have unpredictable behaviour if the
> identity is violated.
>
> Mark
>
More information about the Python-Dev
mailing list