[Python-Dev] Semantics of __int__(), __index__()

Tim Delaney tim.delaney at aptare.com
Thu Apr 4 22:50:58 CEST 2013


On 5 April 2013 02:16, Ethan Furman <ethan at stoneleaf.us> wrote:

> On 04/04/2013 08:01 AM, Chris Angelico wrote:
>
>> On Fri, Apr 5, 2013 at 1:59 AM, Guido van Rossum <guido at python.org>
>> wrote:
>>
>>> On Thu, Apr 4, 2013 at 7:47 AM, Chris Angelico <rosuav at gmail.com> wrote:
>>>
>>>> Is there any argument that I can pass to Foo() to get back a Bar()?
>>>> Would anyone expect there to be one? Sure, I could override __new__ to
>>>> do stupid things, but in terms of logical expectations, I'd expect
>>>> that Foo(x) will return a Foo object, not a Bar object. Why should int
>>>> be any different? What have I missed here?
>>>>
>>>
>>>
>>> A class can define a __new__ method that returns a different object. E.g.
>>> (python 3):
>>>
>>
>> Right, I'm aware it's possible. But who would expect it of a class?
>>
>
> FTR I'm in the int() should return an int camp, but to answer your
> question: my dbf module has a Table class, but it returns either a
> Db3Table, FpTable, VfpTable, or ClpTable depending on arguments (if
> creating a new one) or the type of the table in the existing dbf file.
>

I fall into:

1. int(), float(), str() etc should return that exact class (and
operator.index() should return exactly an int).

2. It could sometimes be useful for __int__() and __index__() to return a
subclass of int.

So, for the int constructor, I would have the following logic (assume
appropriate try/catch):

def __new__(cls, obj):
    i = obj.__int__()

    if type(i) is int:
        return i

    return i._internal_value

Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20130405/55ecb703/attachment.html>


More information about the Python-Dev mailing list