Skip to content

Commit

Permalink
feat: add default encoder for Pattern type
Browse files Browse the repository at this point in the history
closes #2045
  • Loading branch information
PrettyWood committed Oct 27, 2020
1 parent 95435de commit fdd0365
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 0 deletions.
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
4 changes: 4 additions & 0 deletions pydantic/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def isoformat(o: Union[datetime.date, datetime.time]) -> str:

def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from re import Pattern

from .main import BaseModel

Expand All @@ -54,6 +55,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 fdd0365

Please sign in to comment.