[Python-Dev] Semantics of int(), index() (original) (raw)

Mark Shannon mark at hotpy.org
Sun Mar 31 15:29:58 CEST 2013


Hi all,

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 odd behaviour.

Defining two classes:

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'

type(int(i2)) new <class '__main__.Int2'> <class '__main__.Int2'>

Why is a new Int2 being created?

operator.index does similar things.

So,

  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())? where: def int_check(x): if is_int(x): return x else: raise TypeError(...)

def index_check(x): if is_index(x): return x else: raise TypeError(...)

The definition of is_int(x) and is_index(x) follow from the answers to 1 and 2.

I had previously assumed (and would expect) that the answers were:

  1. Any subclass is OK
  2. Ditto
  3. Yes
  4. Yes Which means that def is_int(x): return int in type(x).mro is_index = is_int

Cheers, Mark.



More information about the Python-Dev mailing list