cython-devel
changeset 2082:51fa7e425dc8
Ticket #326, coerce -1 to -2 for __hash__
| author | Robert Bradshaw <robertwb@math.washington.edu> |
|---|---|
| date | Wed Jun 03 03:17:42 2009 -0700 (4 years ago) |
| parents | 88fa346e169d |
| children | f5937b247e12 |
| files | Cython/Compiler/Nodes.py tests/run/hash_T326.pyx |
line diff
1.1 --- a/Cython/Compiler/Nodes.py Tue May 26 22:54:46 2009 +0200
1.2 +++ b/Cython/Compiler/Nodes.py Wed Jun 03 03:17:42 2009 -0700
1.3 @@ -1228,6 +1228,11 @@
1.4
1.5 code.put_finish_refcount_context()
1.6
1.7 + if self.entry.is_special and self.entry.name == "__hash__":
1.8 + # Returning -1 for __hash__ is supposed to signal an error
1.9 + # We do as Python instances and coerce -1 into -2.
1.10 + code.putln("if (unlikely(%s == -1) && !PyErr_Occurred()) %s = -2;" % (Naming.retval_cname, Naming.retval_cname))
1.11 +
1.12 if acquire_gil:
1.13 code.putln("PyGILState_Release(_save);")
1.14
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/tests/run/hash_T326.pyx Wed Jun 03 03:17:42 2009 -0700
2.3 @@ -0,0 +1,29 @@
2.4 +__doc__ = u"""
2.5 +
2.6 + >>> hash(A(5))
2.7 + 5
2.8 + >>> hash(A(-1))
2.9 + -2
2.10 + >>> hash(A(-2))
2.11 + -2
2.12 + >>> hash(A(100))
2.13 + Traceback (most recent call last):
2.14 + ...
2.15 + TypeError: That's kind of a round number...
2.16 +
2.17 + >>> __hash__(-1)
2.18 + -1
2.19 +"""
2.20 +
2.21 +cdef class A:
2.22 + cdef long a
2.23 + def __init__(self, a):
2.24 + self.a = a
2.25 + def __hash__(self):
2.26 + if self.a == 100:
2.27 + raise TypeError, "That's kind of a round number..."
2.28 + else:
2.29 + return self.a
2.30 +
2.31 +cpdef long __hash__(long x):
2.32 + return x
