Skip to content

Commit

Permalink
feat: add default encoder for Pattern type (#2056)
Browse files Browse the repository at this point in the history
closes #2045
  • Loading branch information
PrettyWood committed Nov 29, 2020
1 parent 9cb7ca7 commit 4020ebc
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 1 deletion.
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

0 comments on commit 4020ebc

Please sign in to comment.