>>> import json
>>> from enum import Enum
>>> class AStringEnum(str, Enum):
... A = "a"
...
>>> val = AStringEnum.A
>>> json.dumps(val)
'"a"'
>>> in_dict = json.dumps({"key": val})
>>> in_dict
'{"key": "AStringEnum.A"}'
>>> parsed = json.loads(in_dict)
>>> type(parsed['key'])
<class 'str'>
>>> repr(parsed['key'])
"'AStringEnum.A'"
>>> AStringEnum(parsed['key'])
Traceback (most recent call last):
File "<python-input-15>", line 1, in <module>
AStringEnum(parsed['key'])
~~~~~~~~~~~^^^^^^^^^^^^^^^
File "/usr/lib64/python3.15/enum.py", line 732, in __call__
return cls.__new__(cls, value)
~~~~~~~~~~~^^^^^^^^^^^^
File "/usr/lib64/python3.15/enum.py", line 1221, in __new__
raise ve_exc
ValueError: 'AStringEnum.A' is not a valid AStringEnum
>>> import json
>>> from enum import Enum
>>> class AStringEnum(str, Enum):
... A = "a"
...
>>> val = AStringEnum.A
>>> json.dumps(val)
'"a"'
>>> json.dumps({"key": val})
'{"key": "a"}'
>>> in_dict = json.dumps({"key": val})
>>> parsed = json.loads(in_dict)
>>> type(parsed['key'])
<class 'str'>
>>> repr(parsed['key'])
"'a'"
>>> AStringEnum(parsed['key'])
<AStringEnum.A: 'a'>
Bug report
Bug description:
Cross posting from cattrs: python-attrs/cattrs#744
There's a difference in how Python 3.14 and Pytthon 3.15 handle json serialization of string enum values stored in other types which is exposed by cattrs tests.
I have failed to find any track record for this behavior in the available docs.
See:
Python 3.15.0a7
>>> import json >>> from enum import Enum >>> class AStringEnum(str, Enum): ... A = "a" ... >>> val = AStringEnum.A >>> json.dumps(val) '"a"' >>> in_dict = json.dumps({"key": val}) >>> in_dict '{"key": "AStringEnum.A"}' >>> parsed = json.loads(in_dict) >>> type(parsed['key']) <class 'str'> >>> repr(parsed['key']) "'AStringEnum.A'" >>> AStringEnum(parsed['key']) Traceback (most recent call last): File "<python-input-15>", line 1, in <module> AStringEnum(parsed['key']) ~~~~~~~~~~~^^^^^^^^^^^^^^^ File "/usr/lib64/python3.15/enum.py", line 732, in __call__ return cls.__new__(cls, value) ~~~~~~~~~~~^^^^^^^^^^^^ File "/usr/lib64/python3.15/enum.py", line 1221, in __new__ raise ve_exc ValueError: 'AStringEnum.A' is not a valid AStringEnumPython 3.14.3
CPython versions tested on:
3.15
Operating systems tested on:
Linux
Linked PRs