Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Python3: hex() on arbitrary classes

2 views
Skip to first unread message

Philipp Hagemeister

unread,
Sep 1, 2009, 11:22:31 AM9/1/09
to pytho...@python.org
class X(object):
def __int__(self): return 42
def __hex__(self): return '2b' #sic

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


signature.asc

Mark Dickinson

unread,
Sep 1, 2009, 12:21:45 PM9/1/09
to

__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 Hagemeister

unread,
Sep 1, 2009, 12:31:41 PM9/1/09
to Mark Dickinson, pytho...@python.org
Mark Dickinson wrote:
> (...) 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:
Thanks. Somehow forgot this magic method and deleted it by accident.

Philipp

signature.asc

Mark Dickinson

unread,
Sep 2, 2009, 3:07:33 AM9/2/09
to
On Sep 1, 5:31 pm, Philipp Hagemeister <phi...@phihag.de> wrote:
> Mark Dickinson wrote:
> > (...) 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:
>
> Thanks. Somehow forgot this magic method and deleted it by accident.

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

0 new messages