[Python-Dev] Fwd: str(IntEnum)

Ian Cordasco graffatcolmingov at gmail.com
Sat Feb 21 04:03:37 CET 2015


On Fri, Feb 20, 2015 at 12:36 PM, Florian Bruhin <me at the-compiler.org> wrote:
> * Demian Brecht <demianbrecht at gmail.com> [2015-02-20 10:24:53 -0800]:
>> These and other implementations return a string representation of the instance’s value, not a string representation of the object itself. Whereas elsewhere in the standard library:
>>
>> >>> str(ProtocolError('url', 42, 'msg', ''))
>> '<ProtocolError for url: 42 msg>’
>> >>> str(URLError('reason'))
>> '<urlopen error reason>’
>> >>> str(Cookie(0, '', '', '4', '', '', '', '', '', '', '', 0, '', '', '', ''))
>> '<Cookie = for :4>'
>>
>> The specific problem that I encountered was when swapping an IntEnum implementation for ints in http.client, which caused a change in logging output (from int.__str__ to Enum.__str__) , which was a bit of a surprise, especially given the value is a builtin type.
>>
>> I think that a decent rule around the usage of __str__ is that it should be a string representation of the value, not of the object. Failing the ability to logically coerce the value to a string, it should simply fall back to repr(obj).
>>
>> Of course, I realize that the chances of this change being made to such a fundamental (and largely inconsequential) feature are likely nil, but I thought I’d share my thoughts anyways.
>
>     >>> foo = object()
>     >>> str(foo)
>     '<object object at 0x7f799a8a9070>'
>     >>> repr(foo)
>     '<object object at 0x7f799a8a9070>'
>
> This is exactly what you see above. ;)
>
> Florian
>
> --
> http://www.the-compiler.org | me at the-compiler.org (Mail/XMPP)
>    GPG: 916E B0C8 FD55 A072 | http://the-compiler.org/pubkey.asc
>          I love long mails! | http://email.is-not-s.ms/

There's a semantic difference between an int and an IntEnum (or
subclass thereof). MyEnum.FOO is a MyEnum type. IntEnums just happen
to behave like an int under certain circumstances. That doesn't mean
it needs to act like it in all. Further, it can be turned into an int
if you want to represent it as an int, e.g., str(int(MyEnum.FOO)) ==
str(1). I hope this helps.


More information about the Python-Dev mailing list