[Python-ideas] Change magic strings to enums

Jacco van Dorp j.van.dorp at deonet.nl
Mon Apr 30 03:04:08 EDT 2018


2018-04-26 15:26 GMT+02:00 Nick Coghlan <ncoghlan at gmail.com>:
> On 26 April 2018 at 19:37, Jacco van Dorp <j.van.dorp at deonet.nl> wrote:
>> I'm kind of curious why everyone here seems to want to use IntFlags
>> and other mixins. The docs themselves say that their use should be
>> minimized, and tbh I agree with them. Backwards compatiblity can be
>> maintained by allowing the old value and internally converting it to
>> the enum. Combinability is inherent to enum.Flags. There'd be no real
>> reason to use mixins as far as I can see ?
>
> Serialisation formats are a good concrete example of how problems can
> arise by switching out concrete types on people:
>
>>>> import enum, json
>>>> a = "A"
>>>> class Enum(enum.Enum):
> ...     a = "A"
> ...
>>>> class StrEnum(str, enum.Enum):
> ...     a = "A"
> ...
>>>> json.dumps(a)
> '"A"'
>>>> json.dumps(StrEnum.a)
> '"A"'
>>>> json.dumps(Enum.a)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/usr/lib64/python3.6/json/__init__.py", line 231, in dumps
>     return _default_encoder.encode(obj)
>   File "/usr/lib64/python3.6/json/encoder.py", line 199, in encode
>     chunks = self.iterencode(o, _one_shot=True)
>   File "/usr/lib64/python3.6/json/encoder.py", line 257, in iterencode
>     return _iterencode(o, 0)
>   File "/usr/lib64/python3.6/json/encoder.py", line 180, in default
>     o.__class__.__name__)
> TypeError: Object of type 'Enum' is not JSON serializable
>
> The mixin variants basically say "If you run into code that doesn't
> natively understand enums, act like an instance of this type".
>
> Since most of the standard library has been around for years, and
> sometimes even decades, we tend to face a *lot* of backwards
> compatibility requirements along those lines.
>
> Cheers,
> Nick.

However, as the docs not, they will be comparable with each other,
which should throw an error. Since this is only a problem for this
case when serializing (since the functions would allow the old str
arguments for probably ever), shouldn't this be something caught when
you upgrade the version you run your script under ?

It's also a rather simple fix: json.dumps(Enum.a.value) would work just fine.

Now im aware that most people don't have 100% test coverage and such.
I also rather lack the amount of experience you guys have.

Guess im just a bit behind on the practicality beats purity here :)

Jacco


More information about the Python-ideas mailing list