[pypy-svn] r73003 - in pypy/branch/cpython-extension/pypy/module/cpyext: . test

agaynor at codespeak.net agaynor at codespeak.net
Sun Mar 28 00:31:57 CET 2010


Author: agaynor
Date: Sun Mar 28 00:31:56 2010
New Revision: 73003

Modified:
   pypy/branch/cpython-extension/pypy/module/cpyext/floatobject.py
   pypy/branch/cpython-extension/pypy/module/cpyext/test/test_floatobject.py
Log:
Implemented PyNumber_Float.

Modified: pypy/branch/cpython-extension/pypy/module/cpyext/floatobject.py
==============================================================================
--- pypy/branch/cpython-extension/pypy/module/cpyext/floatobject.py	(original)
+++ pypy/branch/cpython-extension/pypy/module/cpyext/floatobject.py	Sun Mar 28 00:31:56 2010
@@ -1,5 +1,6 @@
 from pypy.rpython.lltypesystem import rffi, lltype
 from pypy.module.cpyext.api import cpython_api, PyObject
+from pypy.interpreter.error import OperationError
 
 @cpython_api([lltype.Float], PyObject)
 def PyFloat_FromDouble(space, value):
@@ -8,3 +9,14 @@
 @cpython_api([PyObject], lltype.Float, error=-1)
 def PyFloat_AsDouble(space, w_obj):
     return space.float_w(space.float(w_obj))
+
+
+ at cpython_api([PyObject], PyObject)
+def PyNumber_Float(space, w_obj):
+    """
+    Returns the o converted to a float object on success, or NULL on failure.
+    This is the equivalent of the Python expression float(o)."""
+    try:
+        return space.float(w_obj)
+    except OperationError:
+        return None

Modified: pypy/branch/cpython-extension/pypy/module/cpyext/test/test_floatobject.py
==============================================================================
--- pypy/branch/cpython-extension/pypy/module/cpyext/test/test_floatobject.py	(original)
+++ pypy/branch/cpython-extension/pypy/module/cpyext/test/test_floatobject.py	Sun Mar 28 00:31:56 2010
@@ -1,4 +1,5 @@
 from pypy.module.cpyext.test.test_api import BaseApiTest
+from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
 
 class TestFloatObject(BaseApiTest):
     def test_floatobject(self, space, api):
@@ -7,3 +8,25 @@
 
         assert api.PyFloat_AsDouble(space.w_None) == -1
         api.PyErr_Clear()
+
+class AppTestFloatObject(AppTestCpythonExtensionBase):
+    def test_float(self):
+        module = self.import_extension("foo", [
+        ("test_float_coerce", "METH_NOARGS",
+        """
+            PyObject *p = PyNumber_Float(PyTuple_GetItem(args, 0));
+            if (p != NULL) {
+                return p;
+            }
+            Py_RETURN_NONE;
+        """),
+        ])
+        
+        assert type(module.test_float_coerce(3)) is float
+        assert module.test_float_coerce([]) is None
+        
+        class Coerce(object):
+            def __float__(self):
+                return 42.5
+        
+        assert module.test_float_coerce(Coerce()) == 42.5



More information about the Pypy-commit mailing list