MCPcopy
hub / github.com/pydantic/pydantic / constr

Function constr

pydantic/types.py:752–834  ·  view source on GitHub ↗

!!! warning "Discouraged" This function is **discouraged** in favor of using [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with [`StringConstraints`][pydantic.types.StringConstraints] instead. This function will be **deprecated**

(
    *,
    strip_whitespace: bool | None = None,
    to_upper: bool | None = None,
    to_lower: bool | None = None,
    strict: bool | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | Pattern[str] | None = None,
    ascii_only: bool | None = None,
)

Source from the content-addressed store, hash-verified

750
751
752def constr(
753 *,
754 strip_whitespace: bool | None = None,
755 to_upper: bool | None = None,
756 to_lower: bool | None = None,
757 strict: bool | None = None,
758 min_length: int | None = None,
759 max_length: int | None = None,
760 pattern: str | Pattern[str] | None = None,
761 ascii_only: bool | None = None,
762) -> type[str]:
763 """
764 !!! warning "Discouraged"
765 This function is **discouraged** in favor of using
766 [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
767 [`StringConstraints`][pydantic.types.StringConstraints] instead.
768
769 This function will be **deprecated** in Pydantic 3.0.
770
771 The reason is that `constr` returns a type, which doesn't play well with static analysis tools.
772
773 === ":x: Don't do this"
774 ```python
775 from pydantic import BaseModel, constr
776
777 class Foo(BaseModel):
778 bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')
779 ```
780
781 === ":white_check_mark: Do this"
782 ```python
783 from typing import Annotated
784
785 from pydantic import BaseModel, StringConstraints
786
787 class Foo(BaseModel):
788 bar: Annotated[
789 str,
790 StringConstraints(
791 strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$'
792 ),
793 ]
794 ```
795
796 A wrapper around `str` that allows for additional constraints.
797
798 ```python
799 from pydantic import BaseModel, constr
800
801 class Foo(BaseModel):
802 bar: constr(strip_whitespace=True, to_upper=True)
803
804 foo = Foo(bar=' hello ')
805 print(foo)
806 #> bar='HELLO'
807 ```
808
809 Args:

Callers 8

test_schema_dict_constrFunction · 0.90
ModelClass · 0.90
ConStringModelClass · 0.90
ModelClass · 0.90
CheckModelClass · 0.90
MoreStringsModelClass · 0.90
FoobarClass · 0.90

Calls 1

StringConstraintsClass · 0.85

Tested by 1

test_schema_dict_constrFunction · 0.72