Skip to content

Commit

Permalink
Fix json_encoders for Enum subclasses (#7029)
Browse files Browse the repository at this point in the history
  • Loading branch information
adriangb committed Aug 8, 2023
1 parent 3e7a024 commit 2efd665
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
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')}

0 comments on commit 2efd665

Please sign in to comment.