From: <pj...@us...> - 2008-10-30 06:06:04
|
Revision: 5529 http://jython.svn.sourceforge.net/jython/?rev=5529&view=rev Author: pjenvey Date: 2008-10-30 06:06:03 +0000 (Thu, 30 Oct 2008) Log Message: ----------- allow NotImplemented and non ints that can be converted in Derived __cmp__ results Modified Paths: -------------- trunk/jython/Lib/test/test_cmp_jy.py trunk/jython/src/templates/object.derived Modified: trunk/jython/Lib/test/test_cmp_jy.py =================================================================== --- trunk/jython/Lib/test/test_cmp_jy.py 2008-10-30 03:05:31 UTC (rev 5528) +++ trunk/jython/Lib/test/test_cmp_jy.py 2008-10-30 06:06:03 UTC (rev 5529) @@ -31,12 +31,37 @@ assert (-2 < 'a') assert not (-1 == 'a') +class CustomCmp(unittest.TestCase): + def test___cmp___returns(self): + class Foo(object): + def __int__(self): + return 0 + class Bar(object): + def __int__(self): + raise ValueError('doh') + class Baz(object): + def __cmp__(self, other): + return self.cmp(other) + baz = Baz() + baz.cmp = lambda other : Foo() + self.assertEqual(cmp(100, baz), 0) + baz.cmp = lambda other : NotImplemented + self.assertEqual(cmp(100, baz), 1) + baz.cmp = lambda other: Bar() + self.assertRaises(ValueError, cmp, 100, baz) + baz.cmp = lambda other: 1 / 0 + self.assertRaises(ZeroDivisionError, cmp, 100, baz) + del Baz.__cmp__ + # CPython handles numbers differently than other types in + # object.c:default_3way_compare, and gets 1 here. we don't care + self.assert_(cmp(100, baz) in (-1, 1)) def test_main(): test_support.run_unittest( UnicodeDerivedCmp, LongDerivedCmp, IntStrCmp, + CustomCmp ) if __name__ == '__main__': Modified: trunk/jython/src/templates/object.derived =================================================================== --- trunk/jython/src/templates/object.derived 2008-10-30 03:05:31 UTC (rev 5528) +++ trunk/jython/src/templates/object.derived 2008-10-30 06:06:03 UTC (rev 5529) @@ -110,11 +110,11 @@ return super.__cmp__(other); } PyObject res = impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v < 0 ? -1 : v > 0 ? 1 : 0; + if (res == Py.NotImplemented) { + return -2; } - throw Py.TypeError("__cmp__ should return a int"); + int c = res.asInt(); + return c < 0 ? -1 : c > 0 ? 1 : 0; } public boolean __nonzero__() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |