[Python-ideas] Stop displaying elements of bytes objects as printable ASCII characters in CPython 3
Steven D'Aprano
steve at pearwood.info
Mon Sep 15 16:44:15 CEST 2014
On Mon, Sep 15, 2014 at 07:24:17AM -0700, Ethan Furman wrote:
> >In Python 2, hex() calls the dunder method __hex__. That has been
> >removed in Python 3. Does anyone know why?
>
> __hex__ and __oct__ were removed in favor of __index__. __index__ returns
> the number as an integer (if possible to do so without conversion from,
> say, float or complex or ...). __hex__ and __oct__ did the same, and were
> redundant.
No, __hex__ returned a string. It could be used to implement (say) a
floating point hex representation, or hex() of bytes.
py> (42).__hex__()
'0x2a'
In Python 2, hex() only had to return a string, and accepted anything
with a __hex__ method. In Python 3, it can only be used on objects which
are int-like, which completely rules out conversions of non-ints to
hexadecimal notation.
py> class MyList(list):
... def __hex__(self):
... return '[' + ', '.join(hex(a) for a in self) + ']'
...
py> l = MyList([21, 16, 256, 73])
py> hex(l)
'[0x15, 0x10, 0x100, 0x49]'
Pity.
I don't suppose anyone would support bringing back __hex__?
--
Steven
More information about the Python-ideas
mailing list