]> granicus.if.org Git - python/commitdiff
call __float__ on str subclasses #5759
authorBenjamin Peterson <benjamin@python.org>
Wed, 15 Apr 2009 21:26:36 +0000 (21:26 +0000)
committerBenjamin Peterson <benjamin@python.org>
Wed, 15 Apr 2009 21:26:36 +0000 (21:26 +0000)
tests by R. David Murray

Lib/test/test_float.py
Misc/NEWS
Objects/floatobject.c

index 2b6bd781cab070e23e439aec31065074e2ded042..0b1ae96495bc9c27a3cf0ae7cab8398b6ee22ddd 100644 (file)
@@ -82,11 +82,23 @@ class GeneralFloatCases(unittest.TestCase):
             def __float__(self):
                 return 42
 
+        # Issue 5759: __float__ not called on str subclasses (though it is on
+        # unicode subclasses).
+        class FooStr(str):
+            def __float__(self):
+                return float(str(self)) + 1
+
+        class FooUnicode(unicode):
+            def __float__(self):
+                return float(unicode(self)) + 1
+
         self.assertAlmostEqual(float(Foo0()), 42.)
         self.assertAlmostEqual(float(Foo1()), 42.)
         self.assertAlmostEqual(float(Foo2()), 42.)
         self.assertAlmostEqual(float(Foo3(21)), 42.)
         self.assertRaises(TypeError, float, Foo4(42))
+        self.assertAlmostEqual(float(FooUnicode('8')), 9.)
+        self.assertAlmostEqual(float(FooStr('8')), 9.)
 
     def test_floatasratio(self):
         for f, ratio in [
index 4c30c03e5c881ad91eb1ef82cdb1e7c793444729..8577a9f3c9367480b5cc6b66292a548038b2db9d 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -12,6 +12,8 @@ What's New in Python 2.7 alpha 1
 Core and Builtins
 -----------------
 
+- Issue #5759: float() didn't call __float__ on str subclasses.
+
 - Issue #5704: the "-3" command-line option now implies "-t".
 
 - Issue #2170: refactored xml.dom.minidom.normalize, increasing both
index 881671c251c6a51310f21bf733c3970ae362db0d..4f041f4820cce51d28dff0ec63ac85ceff515c7d 100644 (file)
@@ -1630,7 +1630,9 @@ float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
                return float_subtype_new(type, args, kwds); /* Wimp out */
        if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
                return NULL;
-       if (PyString_Check(x))
+       /* If it's a string, but not a string subclass, use
+          PyFloat_FromString. */
+       if (PyString_CheckExact(x))
                return PyFloat_FromString(x, NULL);
        return PyNumber_Float(x);
 }