[Python-ideas] Enum and serialization

Ethan Furman ethan at stoneleaf.us
Thu Jul 18 20:24:26 CEST 2013


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.

--
~Ethan~


More information about the Python-ideas mailing list