On Feb 19, 12:58 am, Simon King <simon.k...@uni-jena.de> wrote:

> Here I am not sure: Must hash be compatible with cmp or with rich
> comparison?

Neither :-). It's up to the class writer to decide if they want
something usable :-)

> Hence, should I overload __cmp__ as well?

If you look at the C-API rules, inheritance of tp_compare,
tp_richcompare and tp_hash is simultaneous: Only if a subclass
implements none of them (they are set to NULL) do they get inherited.
That means a "tp_richcompare/tp_compare" pair never gets broken up.
Since "__richcmp__" is preferred over "__cmp__" for "==", your
"__cmp__" will never be used for "==" if it's installed next to a
"__richcmp__".

The C-code also explicitly checks whether "__eq__" lives in the
tp_dict of the type object and prints a warning if it does, even if
all required tp_* slots are NULL:

PyErr_WarnPy3k("Overriding "
"__eq__ blocks inheritance "
 "of __hash__ in 3.x",1)

which suggests that Python 3 has some additional rules (can extension
classes simply implement "__eq__" rather than provide
"tp_richcompare"?).

Some small experiments with "class" definitions in Python 2.7 itself
suggest that the rules there are a lot laxer: I wasn't able to observe
any restrictions:

sage: class A(object):
....:     def __eq__(a,b):
....:         return True
....:
sage: hash(A())
4727009
sage: class B(object):
....:     def __cmp__(a,b):
....:         return 0
....:
sage: hash(B())
4794121

So oddly enough, the very strict semantics on Python C-API level seem
to be largely covered up in Python language level. Still, I think
Python would search the entire MRO for an "__eq__" that does the trick
before using "__cmp__".

Another caveat is that "!=" does not need to be the negation of "==".
However, in you implementation it is, so that only gets broken if the
user explicitly provides a "__ne__" but not a "__eq__".

-- 
You received this message because you are subscribed to the Google Groups 
"sage-devel" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sage-devel+unsubscr...@googlegroups.com.
To post to this group, send email to sage-devel@googlegroups.com.
Visit this group at http://groups.google.com/group/sage-devel?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to