[Python-checkins] python/dist/src/Objects listobject.c,2.134,2.135
Guido van Rossum
guido@python.org
2002年9月05日 15:51:26 -0400
> Guido van Rossum wrote:
> >
> > > I think they added the three-way if tests to handle cases where
> > > an object instance defined a rich comparison operator and
> > > returned something other than -1, 0, or 1. At one time, I
> > > think 2 and/or -2 had a meaning. But then, I could be confusing
> > > it with another story.
> >
> > In the past, the 3way comparison was unclear about this. Then a
> > convention was added that when it sets an exception, a negative number
> > should be returned; then this was tightened (in most places?) to
> > require -1 for exceptions.
> >
> > Then I wrote some code that uses additional conventions for new APIs:
> > -2 for errors, +2 for NotImplemented. I am hoping that at some point
> > in the future we can add this convention to the tp_compare slot
> > functions, but it's not there yet. We'll have to go through a period
> > where these are only supposed to return -2, -1, 0 or 1, and only -2
> > and -1 are allowed for errors; then encourage -2 for errors; finally
> > allow +2 for NotImplemented.
>> Would it be best for sq_contains to only return -1, 0, and 1 or
> return the same values as PyObject_RichCompare()?
Huh? PyObject_RichCompare() returns a PyObject *. Maybe you mean
PyObject_RichCompareBool()? It says:
/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Compare PySequence_Contains():
/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
* Use sq_contains if possible, else defer to _PySequence_IterSearch().
*/
int
PySequence_Contains(PyObject *seq, PyObject *ob)
{
if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
if (sqm != NULL && sqm->sq_contains != NULL)
return (*sqm->sq_contains)(seq, ob);
}
return _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
}
It looks like it already uses the same convention (though doesn't
verify that sq_contains doesn't return anything else).
Or maybe I'm misunderstanding? Did you want to add the
'2=>NotImplemented' convention? That's not backwards compatible I believe.
> Also the same optimization made to list_contains() can be
> made for tuplecontains().
Sure, go ahead.
--Guido van Rossum (home page: http://www.python.org/~guido/)