[Python-ideas] Enum and serialization
Nick Coghlan
ncoghlan at gmail.com
Fri Jul 19 07:11:13 CEST 2013
On 19 July 2013 04:24, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 07/18/2013 11:13 AM, Giampaolo Rodola' wrote:
>>
>> I just received this bug report in psutil:
>> https://code.google.com/p/psutil/issues/detail?id=408
>>
>> Long story short, in psutil I have defined a constant type:
>> http://code.activestate.com/recipes/577984-named-constant-type/
>> https://code.google.com/p/psutil/source/browse/psutil/_common.py#31
>> ...behaving along these lines:
>>
>>>>> FOO = constant(0, 'FOO')
>>>>> FOO
>>
>> 0
>>>>>
>>>>> str(FOO)
>>
>> 'FOO'
>>
>> It's a nasty problem and I'm still not sure how to solve it in psutil
>> but this got me thinking about PEP 435 (Adding an Enum type to the
>> Python standard library) since the two things are kind of related.
>> I haven't properly gone through the PEP yet (I will) but I notice it
>> doesn't talk about serialization.
>> Has it been considered?
>
>
> See http://bugs.python.org/issue18264.
>
> The basic issue is that json only knows how to serialize built-in types. As
> soon as we build on that, json barfs.
>
> One way around that is to write your own json handler that knows about your
> custom types.
>
> For the 3.4 stdlib there are two proposals on the table:
>
> 1) for IntEnum and FloatEnum cast the member to int or float, then
> procede;
>
> 2) for any Enum, extract the value and proceed.
3) Only change repr (not str) in IntEnum
I know Guido doesn't like it, but I still think the backwards
compatibility risk is too high to use them to replace constants in the
standard library if they change the output of __str__. Debugging only
needs repr, and we can make sure stdlib error messages use repr, too.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list