[Python-Dev] PySequence_Contains
Guido van Rossum
guido@digicool.com
Sat, 05 May 2001 07:24:19 -0500
In a checkin message, Tim wrote:
> The full story for instance objects is pretty much unexplainable, because
> instance_contains() tries its own flavor of iteration-based containment
> testing first, and PySequence_Contains doesn't get a chance at it unless
> instance_contains() blows up. A consequence is that
> some_complex_number in some_instance
> dies with a TypeError unless some_instance.__class__ defines __iter__ but
> does not define __getitem__.
This kind of thing happens everywhere -- instances always define all
slots but using the slots sometimes fails when the corresponding
__foo__ doesn't exist. Decisions based on the presence or absence of
a slot are therefore in general not reliable; the only exception is
the decision to *call* the slot or not. The correct solution is not
to catch AttributeError and pretend that the slot didn't exist (which
would mask an AttributeError occurring inside the __contains__ method
if there was one), but to reimplement the default behavior in the
instance slot implementation.
In this case, that means that PySequence_Contains() can be simplified
(no need to test for AttributeError), and instance_contains() should
fall back to a loop over iter(self) rather than trying to use
instance_item().
--Guido van Rossum (home page: http://www.python.org/~guido/)