hex(X())
What would you expect? Python2 returns '2b', but python 3(74624) throws
TypeError: 'X' object cannot be interpreted as an integer. Why doesn't
python convert the object to int before constructing the hex string?
Regards,
Philipp Hagemeister
__hex__ is no longer a magic method in Python 3. If you want to be
able to interpret instances of X as integers in the various Python
contexts that expect integers (e.g., hex(), but also things like list
indexing), you should implement the __index__ method:
Python 3.2a0 (py3k:74624, Sep 1 2009, 16:53:00)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class X:
... def __index__(self): return 3
...
>>> hex(X())
'0x3'
>>> range(10)[X()]
3
>>> 'abc' * X()
'abcabcabc'
--
Mark
Philipp
I wonder whether it would make sense for the Python 2.x hex
function to fall back to __index__ when __hex__ isn't defined.
With the current setup, it's not clear how to write 2.x code
that will also run (post 2to3 translation) properly on 3.x.
--
Mark