[Python-Dev] __contains__ hook

Guido van Rossum guido@python.org
Thu, 03 Feb 2000 11:21:37 -0500


> M.-A. Lemburg writes:
>  > Shouldn't 'in' be a slot of the sequence methods ? I'd suggest
>  > creating a new tp_flag bit and then extending tp_as_sequence

Fred Drake:
>   Only if we want to restrict set-like behavior to sequences, and I
> don't think that's clear, though it does mirror the current
> situation.
>   Regardless of the location of the slot, why should a flag be needed?

Because if we add a slot to the as_sequence struct, old extensions
that haven't been recompiled will appear to have garbage in that slot
(because they don't actually have it).  When we use a spare slot in
the main type struct, that problem doesn't exist; but the as_sequence
struct and friends don't have spares.

> Testing the slot for NULL is necessary to avoid core dumps anyway.
> 
>  > plus of course add an abstract function to abstract.c:
>  > 
>  > 	PySequence_Contain(PyObject *container, PyObject *element)
> 
>   There's already PySequence_In(...); see:

That's just a backwards compatibility alias for PySequence_Contains;
see abstract.h.  (PySequence_In() was a bad name, because it has its
arguments reversed with respect to the 'in' operator:
PySequence_In(seq, item) is equivalent to item in seq; you would
expect PySequence_In(item, seq).  The PySequence_Contains name
correctly suggests the (seq, item) argument order.

> 	http://www.python.org/doc/current/api/sequence.html#l2h-135

Maybe the docs need to be updated? (Hint, hint.)

>   I'm inclined to add PyObject_In(...) (or ..._Contains(); I like
> Contains better than In, but there's precedence for In and that's more 
> important) and define the new slot on the Object using one of the
> reserved spaces.  That allows a clean interface for "pure" sets that
> don't have to "look like" sequences or mappings.
> 
>  > which uses the above slot after testing the tp_flag setting.
>  > Python instances, lists, tuples should then support this new
>  > slot. We could even sneak in support for dictionaries once we
>  > decide whether semantics whould be 
> 
>   Bait!

Yuck.  The same argument for disallowing 'x in dict' applies to the C
API.  There's already PyMapping_HasKey().

--Guido van Rossum (home page: http://www.python.org/~guido/)