[issue18738] String formatting (% and str.format) issues with Enum

Eric V. Smith report at bugs.python.org
Thu Aug 15 00:06:40 CEST 2013


Eric V. Smith added the comment:

It's not whether a field width is specified that makes it "empty" or not, it's where there's anything in the format specifier at all. I'm trying to simplify the conversation by using format() instead of str.format(), but I'm not succeeding!

Going back to str.format examples:

'{}'.format(Test.one)
# equivalent to format(Test.one, '')
# result is Test.one.__format__('')

'{:d}'.format(Test.one)
# equivalent to format(Test.one, 'd')
# result is Test.one.__format__('d')

'{:}'.format(Test.one)
# equivalent to format(Test.one, '')
# result is Test.one.__format__('')

'{:10}'.format(Test.one)
# equivalent to format(Test.one, '10')
# result is Test.one.__format__('10')

In all of these cases, since there is no Test.one.__format__, int.__format__ is called. int.__format__ contains logic (Python/formatter_unicode.c, line 1422) that says "if the format specifier is empty, return str(self), otherwise do the int formatting". This is in order to comply with the previously mentioned PEP requirement. That's the only place where there's any "treat this as a str instead of an int" logic.

In order to avoid that logic, and cause more format specifiers to result in str-like behavior, we'll need to implement an __format__ somewhere (IntEnum, I guess) that makes the "int or str" decision.

----------

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


More information about the Python-bugs-list mailing list