[issue19995] hex() and %x, oct() and %o do not behave the same

Terry J. Reedy report at bugs.python.org
Sat Dec 21 00:17:44 CET 2013


Terry J. Reedy added the comment:

It seems to me that anything that is an 'integer' that can be turned into an int without loss of information (has .__index__) is logically a 'number' that can be turned into an int possibly with loss of information (has .__int__).  So perhaps one of the following should be true:

1. The doc for .__index__ specifies that def __index__ 'must' be followed by __int__ = __index__ to make a coherent class. (So Ethan's Grade as written above would not qualify.)

2. The type constructor does this for us by adding __int__ as an alias for __index__ when the latter is present.

3. Every core usage of __int__ looks for __index__ also. Int() does not do this now, but '%d' does, so int(Grade.F) fails but int('%d' % Grade.f) works.

The exact details would depend on whether we want to allow (or at least bless) classes with __int__ and __index__ returning different ints.

The docs for bin/oct/hex(x) are clear. "Convert an integer number to a binary/octal/hexadecimal string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer." This should not change.

If the domain of %x is going to be a subset of of the domain of %d, it seems to me that the exclusion should be of non-integers (such as floats) rather than of non-int integers. Given things as they are, I would simply expand the domain of %x, etc, to that of %d without bothering to go through a deprecation process.

----------
nosy: +terry.reedy
stage:  -> test needed
type:  -> enhancement

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue19995>
_______________________________________


More information about the Python-bugs-list mailing list