Skip to content

String enums in dicts/lists are json serialized differently in Python 3.15 #148241

@befeleme

Description

@befeleme

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 AStringEnum

Python 3.14.3

>>> 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'>

CPython versions tested on:

3.15

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions