[Python-Dev] Semantics of __int__(), __index__()
mark at hotpy.org
Sun Mar 31 15:29:58 CEST 2013
I was looking into http://bugs.python.org/issue17576 and I found that
the semantics of __int__() and __index__() are not precisely defined in
the documentation and that the implementation (CPython 3.4a) has some
Defining two classes:
def __init__(self, val=0):
print("new %s" % self.__class__)
and two instances
i1 = Int1()
i2 = Int2()
we get the following behaviour:
I would have expected 'Int1'
new <class '__main__.Int2'>
Why is a new Int2 being created?
operator.index does similar things.
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__())?
The definition of is_int(x) and is_index(x) follow from the answers to 1
I had previously assumed (and would expect) that the answers were:
1. Any subclass is OK
Which means that
return int in type(x).__mro__
is_index = is_int
More information about the Python-Dev