[Python-Dev] Semantics of __int__(), __index__()
Mark Shannon
mark at hotpy.org
Sun Mar 31 15:29:58 CEST 2013
More information about the Python-Dev mailing list
Sun Mar 31 15:29:58 CEST 2013
- Previous message: [Python-Dev] Idle, site.py, and the release candidates
- Next message: [Python-Dev] Semantics of __int__(), __index__()
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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.
- Previous message: [Python-Dev] Idle, site.py, and the release candidates
- Next message: [Python-Dev] Semantics of __int__(), __index__()
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-Dev mailing list