[Python-Dev] Semantics of int(), index() (original) (raw)
Mark Shannon mark at hotpy.org
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,
- Should type(int(x)) be exactly int, or is any subclass OK?
- Should type(index(x)) be exactly int, or is any subclass OK?
- Should int(x) be defined as int_check(x.int())?
- 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:
- Any subclass is OK
- Ditto
- Yes
- 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 ]