[Python-Dev] Semantics of __int__(), __index__()
Mark Dickinson
dickinsm at gmail.com
Sun Mar 31 16:28:56 CEST 2013
On Sun, Mar 31, 2013 at 2:29 PM, Mark Shannon <mark at hotpy.org> wrote:
> class Int1(int):
> def __init__(self, val=0):
> print("new %s" % self.__class__)
>
> class Int2(Int1):
> def __int__(self):
> return self
>
> and two instances
> i1 = Int1()
> i2 = Int2()
>
> we get the following behaviour:
>
> >>> type(int(i1))
> <class 'int'>
>
> I would have expected 'Int1'
>
Wouldn't that remove the one obvious way to get an 'int' from an 'Int1'?
> 1. Should type(int(x)) be exactly int, or is any subclass OK?
> 2. Should type(index(x)) be exactly int, or is any subclass OK?
> 3. Should int(x) be defined as int_check(x.__int__())?
> 4. Should operator.index(x) be defined as index_check(x.__index__())?
>
For (1), I'd say yes, it should be exactly an int, so my answer to (3) is
no.
As written, int_check would do the wrong thing for bools, too: I
definitely want int(True) to be 1, not True.
For (2) and (4), it's not so clear. Are there use-cases for an __index__
return value that's not directly of type int? I can't think of any offhand.
Mark
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20130331/51c4a9e4/attachment.html>
More information about the Python-Dev
mailing list