From b2d3f333f084012b2cedafc9d6e04ccdc0ee09bd Mon Sep 17 00:00:00 2001 From: Eric Jolibois Date: Tue, 2 Mar 2021 13:05:57 +0100 Subject: [PATCH] refactor: set `Pattern` encoder in `ENCODERS_BY_TYPE` (#2444) * refactor: set `Pattern` encoder in `ENCODERS_BY_TYPE` * docs: add change file --- changes/2444-PrettyWood.md | 1 + pydantic/json.py | 14 ++++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) create mode 100644 changes/2444-PrettyWood.md diff --git a/changes/2444-PrettyWood.md b/changes/2444-PrettyWood.md new file mode 100644 index 0000000000..0d7b9afbf3 --- /dev/null +++ b/changes/2444-PrettyWood.md @@ -0,0 +1 @@ +expose `Pattern` encoder to `fastapi` diff --git a/pydantic/json.py b/pydantic/json.py index 9777a62eb4..81b2698101 100644 --- a/pydantic/json.py +++ b/pydantic/json.py @@ -1,13 +1,21 @@ import datetime +import re +import sys from collections import deque from decimal import Decimal from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path from types import GeneratorType -from typing import Any, Callable, Dict, Pattern, Type, Union +from typing import Any, Callable, Dict, Type, Union from uuid import UUID +if sys.version_info >= (3, 7): + Pattern = re.Pattern +else: + # python 3.6 + Pattern = re.compile('a').__class__ + from .color import Color from .types import SecretBytes, SecretStr @@ -58,6 +66,7 @@ def decimal_encoder(dec_value: Decimal) -> Union[int, float]: IPv6Interface: str, IPv6Network: str, Path: str, + Pattern: lambda o: o.pattern, SecretBytes: str, SecretStr: str, set: list, @@ -75,9 +84,6 @@ 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: