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

Add support re.Pattern[str] to pattern field #9053

Merged
merged 2 commits into from Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 5 additions & 2 deletions pydantic/fields.py
Expand Up @@ -64,7 +64,7 @@ class _FromFieldInfoInputs(typing_extensions.TypedDict, total=False):
strict: bool | None
min_length: int | None
max_length: int | None
pattern: str | None
pattern: str | typing.Pattern[str] | None
allow_inf_nan: bool | None
max_digits: int | None
decimal_places: int | None
Expand Down Expand Up @@ -680,7 +680,7 @@ def Field( # noqa: C901
init: bool | None = _Unset,
init_var: bool | None = _Unset,
kw_only: bool | None = _Unset,
pattern: str | None = _Unset,
pattern: str | typing.Pattern[str] | None = _Unset,
strict: bool | None = _Unset,
gt: float | None = _Unset,
ge: float | None = _Unset,
Expand Down Expand Up @@ -792,6 +792,9 @@ def Field( # noqa: C901
if regex is not None:
raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs')

if isinstance(pattern, typing.Pattern):
pattern = pattern.pattern

if extra:
warn(
'Using extra keyword arguments on `Field` is deprecated and will be removed.'
Expand Down
7 changes: 4 additions & 3 deletions pydantic/types.py
Expand Up @@ -20,6 +20,7 @@
Hashable,
Iterator,
List,
Pattern,
Set,
TypeVar,
Union,
Expand Down Expand Up @@ -696,7 +697,7 @@ class StringConstraints(annotated_types.GroupedMetadata):
strict: bool | None = None
min_length: int | None = None
max_length: int | None = None
pattern: str | None = None
pattern: str | Pattern[str] | None = None

def __iter__(self) -> Iterator[BaseMetadata]:
if self.min_length is not None:
Expand All @@ -715,7 +716,7 @@ def __iter__(self) -> Iterator[BaseMetadata]:
strip_whitespace=self.strip_whitespace,
to_upper=self.to_upper,
to_lower=self.to_lower,
pattern=self.pattern,
pattern=self.pattern.pattern if isinstance(self.pattern, Pattern) else self.pattern,
)


Expand All @@ -727,7 +728,7 @@ def constr(
strict: bool | None = None,
min_length: int | None = None,
max_length: int | None = None,
pattern: str | None = None,
pattern: str | Pattern[str] | None = None,
) -> type[str]:
"""
!!! warning "Discouraged"
Expand Down