]> granicus.if.org Git - python/commitdiff
Fix SF bug #683467, 'int' ability to generate longs not inherited
authorNeal Norwitz <nnorwitz@gmail.com>
Mon, 10 Feb 2003 02:12:43 +0000 (02:12 +0000)
committerNeal Norwitz <nnorwitz@gmail.com>
Mon, 10 Feb 2003 02:12:43 +0000 (02:12 +0000)
When subclassing from an int but not overriding __new__,
long values were not converted properly.  Try to convert
longs into an int.

Lib/test/test_descr.py
Misc/NEWS
Objects/intobject.c

index 8a6a538b4f33f982e8a330f280fdfb8fc098dbe6..8ef7979241956df6e3f9cc06d82dec8e739d06e7 100644 (file)
@@ -458,12 +458,20 @@ def ints():
     class C(int):
         def __add__(self, other):
             return NotImplemented
+    vereq(C(5L), 5)
     try:
         C() + ""
     except TypeError:
         pass
     else:
         raise TestFailed, "NotImplemented should have caused TypeError"
+    import sys
+    try:
+        C(sys.maxint+1)
+    except OverflowError:
+        pass
+    else:
+        raise TestFailed, "should have raised OverflowError"
 
 def longs():
     if verbose: print "Testing long operations..."
index b0683ee87725f491984afda2e6e66363ff1284ff..24f318c88536e55a9f0e11221778ec264283ef4e 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -12,6 +12,9 @@ What's New in Python 2.3 alpha 2?
 Core and builtins
 -----------------
 
+- int subclasses can be initialized with longs if the value fits in an int.
+  See SF bug #683467.
+
 - long(string, base) takes time linear in len(string) when base is a power
   of 2 now.  It used to take time quadratic in len(string).
 
index 915ef21cecd6e8d32c486073004ccade6784ae7d..544e663dac4c37519ae75db1d20ed704cc167a54 100644 (file)
@@ -836,16 +836,30 @@ static PyObject *
 int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 {
        PyObject *tmp, *new;
+       long ival;
 
        assert(PyType_IsSubtype(type, &PyInt_Type));
        tmp = int_new(&PyInt_Type, args, kwds);
        if (tmp == NULL)
                return NULL;
-       assert(PyInt_Check(tmp));
+       if (!PyInt_Check(tmp)) {
+               if (!PyLong_Check(tmp)) {
+                       PyErr_SetString(PyExc_ValueError,
+                                       "value must convertable to an int");
+                       return NULL;
+               }
+               ival = PyLong_AsLong(tmp);
+               if (ival == -1 && PyErr_Occurred())
+                       return NULL;
+
+       } else {
+               ival = ((PyIntObject *)tmp)->ob_ival;
+       }
+
        new = type->tp_alloc(type, 0);
        if (new == NULL)
                return NULL;
-       ((PyIntObject *)new)->ob_ival = ((PyIntObject *)tmp)->ob_ival;
+       ((PyIntObject *)new)->ob_ival = ival;
        Py_DECREF(tmp);
        return new;
 }