Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix json_encoders for Enum subclasses #7029

Merged
merged 1 commit into from Aug 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion pydantic/_internal/_generate_schema.py
Expand Up @@ -242,7 +242,8 @@ def _add_custom_serialization_from_json_encoders(
return schema
# Check the class type and its superclasses for a matching encoder
# Decimal.__class__.__mro__ (and probably other cases) doesn't include Decimal itself
for base in (tp, *tp.__class__.__mro__[:-1]):
# if the type is a GenericAlias (e.g. from list[int]) we need to use __class__ instead of .__mro__
for base in (tp, *getattr(tp, '__mro__', tp.__class__.__mro__)[:-1]):
encoder = json_encoders.get(base)
if encoder is None:
continue
Expand Down
20 changes: 19 additions & 1 deletion tests/test_json.py
Expand Up @@ -7,7 +7,7 @@
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from typing import Any, Generator, Optional, Pattern, Union
from typing import Any, Generator, List, Optional, Pattern, Union
from uuid import UUID

import pytest
Expand Down Expand Up @@ -482,3 +482,21 @@ class Model(BaseModel):
m = Model(x=1)
assert m.model_dump() == {'x': 1}
assert m.model_dump_json() == '{"x":"encoded!"}'


def test_json_encoders_types() -> None:
class MyEnum(Enum):
A = 'a'
B = 'b'

class A(BaseModel):
a: MyEnum
b: List[int]
c: Decimal
model_config = ConfigDict(
json_encoders={Enum: lambda val: val.name, List[int]: lambda val: 'list!', Decimal: lambda val: 'decimal!'}
)

m = A(a=MyEnum.A, b=[1, 2, 3], c=Decimal('0'))
assert m.model_dump_json() == '{"a":"A","b":"list!","c":"decimal!"}'
assert m.model_dump() == {'a': MyEnum.A, 'b': [1, 2, 3], 'c': Decimal('0')}