return an object of a different class

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Feb 18 03:25:39 CET 2011


On Thu, 17 Feb 2011 15:53:14 -0800, Westley Martínez wrote:

>> > Python 3 removed longs because they were ... cryptonic!
>> >
>> Strictly speaking, they weren't removed. ints were removed and long was
>> renamed int.
> My point stands.

Your point is wrong. Ints and longs weren't unified because it is 
"cryptonic" (cryptic?), but to avoid the user needing to care about the 
difference between ints and longs. I've been coding in Python since 
version 1.5, and I can tell you I hated the need to write code like this:


def make_int(obj):
    try:
        return int(obj)
    except ValueError:
        return long(int)

To say nothing of:

def add(x, y):
    try:
        return x+y
    except OverflowError:
        return long(x)+long(y)


Having the int class automatically promote instances to long as needed 
was a HUGE win for simplicity and readability, while still saving memory 
and performance for small ints.

Still not convinced that it's allowed to return objects of a different 
type? From Python 3.1:

>>> reversed
<class 'reversed'>
>>> reversed((1,2,3))
<reversed object at 0x9beb9cc>
>>> reversed("abcd")
<reversed object at 0x9beb9cc>
>>> reversed([1,2,3])
<list_reverseiterator object at 0x9beb70c>
>>> reversed(range(10))
<range_iterator object at 0xb7cd8a88>


-- 
Steven



More information about the Python-list mailing list