Skip to content

Commit d3ffb89

Browse files
committed
python#3777: long(4.2) returned an int, and broke backward compatibility.
the __long__ slot is allowed to return either int or long, but the behaviour of float objects should not change between 2.5 and 2.6. Reviewed by Benjamin Peterson
1 parent 672237d commit d3ffb89

3 files changed

Lines changed: 17 additions & 1 deletion

File tree

‎Lib/test/test_long.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,10 @@ def test_long(self):
279279
self.assertEqual(long(314), 314L)
280280
self.assertEqual(long(3.14), 3L)
281281
self.assertEqual(long(314L), 314L)
282+
# Check that long() of basic types actually returns a long
283+
self.assertEqual(type(long(314)), long)
284+
self.assertEqual(type(long(3.14)), long)
285+
self.assertEqual(type(long(314L)), long)
282286
# Check that conversion from float truncates towards zero
283287
self.assertEqual(long(-3.14), -3L)
284288
self.assertEqual(long(3.9), 3L)

‎Misc/NEWS‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ What's New in Python 2.6 release candidate 1?
1212
Core and Builtins
1313
-----------------
1414

15+
- Issue #3777: long() applied to a float object now always return a long
16+
object; previously an int would be returned for small values. the __long__
17+
method is allowed to return either an int or a long, but the behaviour of
18+
float objects should not change to respect backward compatibility.
19+
1520
- Issue #3751: str.rpartition would perform a left-partition when called with
1621
a unicode argument.
1722

‎Objects/floatobject.c‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1104,6 +1104,13 @@ float_trunc(PyObject *v)
11041104
return PyLong_FromDouble(wholepart);
11051105
}
11061106

1107+
static PyObject *
1108+
float_long(PyObject *v)
1109+
{
1110+
double x = PyFloat_AsDouble(v);
1111+
return PyLong_FromDouble(x);
1112+
}
1113+
11071114
static PyObject *
11081115
float_float(PyObject *v)
11091116
{
@@ -1897,7 +1904,7 @@ static PyNumberMethods float_as_number = {
18971904
0, /*nb_or*/
18981905
float_coerce, /*nb_coerce*/
18991906
float_trunc, /*nb_int*/
1900-
float_trunc, /*nb_long*/
1907+
float_long, /*nb_long*/
19011908
float_float, /*nb_float*/
19021909
0, /* nb_oct */
19031910
0, /* nb_hex */

0 commit comments

Comments
 (0)