Python3: hex() on arbitrary classes

  • Thread starter Philipp Hagemeister
  • Start date
P

Philipp Hagemeister

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



-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEAREKAAYFAkqdPDoACgkQ9eq1gvr7CFyIzQCeKE+C1Wm+KJMAlnZVyjvvJcM9
jnoAoLqGSyxc98uP3UERrBmQ3G1NUQAw
=3oBI
-----END PGP SIGNATURE-----
 
M

Mark Dickinson

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?

__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..... def __index__(self): return 3
....
hex(X()) '0x3'
range(10)[X()] 3
'abc' * X()
'abcabcabc'
 
P

Philipp Hagemeister

Mark said:
(...) 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
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.... def __index__(self): return 3
...
hex(X()) '0x3'
range(10)[X()] 3
'abc' * X()
'abcabcabc'



-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEAREKAAYFAkqdTHAACgkQ9eq1gvr7CFznPgCeNeWG3PY8I+FfahQxDOIQ/E/a
a+8AoKemG9QGvLOfWg1AE+knWwbbkLIH
=D5iJ
-----END PGP SIGNATURE-----
 
M

Mark Dickinson

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top