Strange behaviour: subclass of int returns 3 when constructed with long

Alex Martelli aleax at aleax.it
Sun Feb 9 16:43:14 CET 2003


Gerrit Holl wrote:

> Hi,
> 
>   0 >>> class A(int): pass
>   0 ...
>   1 >>> int(sys.maxint)
> 2147483647
>   2 >>> A(sys.maxint)
> 2147483647
>   3 >>> int(sys.maxint+1)
> 2147483648L
>   4 >>> A(sys.maxint+1)
> 3
>   5 >>> A(sys.maxint+42)
> 3
>   6 >>> int(A(sys.maxint+1))
> 3

In Python 2.3a1, this behavior is indeed reproducible on my
system, too.


> how can this behaviour be explained? Shouldn't A behave identical to int?

int has acquired some magic to generate long instead when needed,
as in your statement number 3.  It apppears the magic isn't
smoothly inherited in 2.3a1.  You may want to signal this bug
in the sourceforge bug tracker.

I think the problem is with int.__new__ being specialcased ONLY
when the class it receives as its argument is int itself -- e.g.:

class A(int):
        def __new__(cls, x): return int.__new__(cls, x)

import sys

print A(sys.maxint+1)

class B(int):
        def __new__(cls, x): return int.__new__(int, x)

import sys

print B(sys.maxint+1)

the first case exhibits the bug, the second one doesn't --
so int.__new__ does seem to be the culprit here.  It may
be using (the C equivalent of) 'cls is int' to condition
its magic, perhaps (haven't checked this in the 2.3a1
Python C sources).


Alex





More information about the Python-list mailing list