diff --git a/changes/1767-PrettyWood.md b/changes/1767-PrettyWood.md new file mode 100644 index 00000000000..7262d7eca70 --- /dev/null +++ b/changes/1767-PrettyWood.md @@ -0,0 +1 @@ +add basic support of Pattern type in schema generation diff --git a/pydantic/schema.py b/pydantic/schema.py index 27c66b2bd37..ec54080e913 100644 --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -14,6 +14,7 @@ Iterable, List, Optional, + Pattern, Sequence, Set, Tuple, @@ -698,6 +699,12 @@ def field_singleton_schema( # noqa: C901 (ignore complexity) field_type = literal_value.__class__ f_schema['const'] = literal_value + # `typing.Pattern` is not a valid type and should be considered as a string. + # Note: We should probably add `pattern: ` in the schema + # but it requires `.schema()` to be an instance method instead of a class one. + if field_type is Pattern: + field_type = str + if lenient_issubclass(field_type, Enum): enum_name = normalize_name(field_type.__name__) f_schema = {'$ref': ref_prefix + enum_name} diff --git a/tests/test_types.py b/tests/test_types.py index 084b9d071a2..0f8c6531072 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -2055,6 +2055,13 @@ class Foobar(BaseModel): f2 = Foobar(pattern=p) assert f2.pattern is p + assert Foobar.schema() == { + 'type': 'object', + 'title': 'Foobar', + 'properties': {'pattern': {'type': 'string', 'title': 'Pattern'}}, + 'required': ['pattern'], + } + def test_pattern_error(): class Foobar(BaseModel):