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

feat: add default encoder for Pattern type #2056

Merged
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
1 change: 1 addition & 0 deletions changes/2045-PrettyWood.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add default encoder for `Pattern` type
5 changes: 4 additions & 1 deletion pydantic/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from typing import Any, Callable, Dict, Pattern, Type, Union
from uuid import UUID

from .color import Color
Expand Down Expand Up @@ -54,6 +54,9 @@ def pydantic_encoder(obj: Any) -> Any:
elif is_dataclass(obj):
return asdict(obj)

if isinstance(obj, Pattern):
return obj.pattern

# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
Expand Down
2 changes: 2 additions & 0 deletions tests/test_json.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime
import json
import re
import sys
from dataclasses import dataclass as vanilla_dataclass
from decimal import Decimal
Expand Down Expand Up @@ -51,6 +52,7 @@ class MyEnum(Enum):
(Decimal('12.34'), '12.34'),
(create_model('BarModel', a='b', c='d')(), '{"a": "b", "c": "d"}'),
(MyEnum.foo, '"bar"'),
(re.compile('^regex$'), '"^regex$"'),
],
)
def test_encoding(input, output):
Expand Down