Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
config.py1297 linesDownload Raw Back to pydantic
1"""Configuration for Pydantic models."""2 3from __future__ import annotations as _annotations4 5import warnings6from re import Pattern7from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar, Union, cast, overload8 9from typing_extensions import TypeAlias, TypedDict, Unpack, deprecated10 11from ._migration import getattr_migration12from .aliases import AliasGenerator13from .errors import PydanticUserError14from .warnings import PydanticDeprecatedSince21115 16if TYPE_CHECKING:17    from ._internal._generate_schema import GenerateSchema as _GenerateSchema18    from .fields import ComputedFieldInfo, FieldInfo19 20__all__ = ('ConfigDict', 'with_config')21 22 23JsonValue: TypeAlias = Union[int, float, str, bool, None, list['JsonValue'], 'JsonDict']24JsonDict: TypeAlias = dict[str, JsonValue]25 26JsonEncoder = Callable[[Any], Any]27 28JsonSchemaExtraCallable: TypeAlias = Union[29    Callable[[JsonDict], None],30    Callable[[JsonDict, type[Any]], None],31]32 33ExtraValues = Literal['allow', 'ignore', 'forbid']34 35 36class ConfigDict(TypedDict, total=False):37    """A TypedDict for configuring Pydantic behaviour."""38 39    title: str | None40    """The title for the generated JSON schema, defaults to the model's name"""41 42    model_title_generator: Callable[[type], str] | None43    """A callable that takes a model class and returns the title for it. Defaults to `None`."""44 45    field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None46    """A callable that takes a field's name and info and returns title for it. Defaults to `None`."""47 48    str_to_lower: bool49    """Whether to convert all characters to lowercase for str types. Defaults to `False`."""50 51    str_to_upper: bool52    """Whether to convert all characters to uppercase for str types. Defaults to `False`."""53 54    str_strip_whitespace: bool55    """Whether to strip leading and trailing whitespace for str types."""56 57    str_min_length: int58    """The minimum length for str types. Defaults to `None`."""59 60    str_max_length: int | None61    """The maximum length for str types. Defaults to `None`."""62 63    extra: ExtraValues | None64    '''65    Whether to ignore, allow, or forbid extra data during model initialization. Defaults to `'ignore'`.66 67    Three configuration values are available:68 69    - `'ignore'`: Providing extra data is ignored (the default):70      ```python71      from pydantic import BaseModel, ConfigDict72 73      class User(BaseModel):74          model_config = ConfigDict(extra='ignore')  # (1)!75 76          name: str77 78      user = User(name='John Doe', age=20)  # (2)!79      print(user)80      #> name='John Doe'81      ```82 83        1. This is the default behaviour.84        2. The `age` argument is ignored.85 86    - `'forbid'`: Providing extra data is not permitted, and a [`ValidationError`][pydantic_core.ValidationError]87      will be raised if this is the case:88      ```python89      from pydantic import BaseModel, ConfigDict, ValidationError90 91 92      class Model(BaseModel):93          x: int94 95          model_config = ConfigDict(extra='forbid')96 97 98      try:99          Model(x=1, y='a')100      except ValidationError as exc:101          print(exc)102          """103          1 validation error for Model104          y105            Extra inputs are not permitted [type=extra_forbidden, input_value='a', input_type=str]106          """107      ```108 109    - `'allow'`: Providing extra data is allowed and stored in the `__pydantic_extra__` dictionary attribute:110      ```python111      from pydantic import BaseModel, ConfigDict112 113 114      class Model(BaseModel):115          x: int116 117          model_config = ConfigDict(extra='allow')118 119 120      m = Model(x=1, y='a')121      assert m.__pydantic_extra__ == {'y': 'a'}122      ```123      By default, no validation will be applied to these extra items, but you can set a type for the values by overriding124      the type annotation for `__pydantic_extra__`:125      ```python126      from pydantic import BaseModel, ConfigDict, Field, ValidationError127 128 129      class Model(BaseModel):130          __pydantic_extra__: dict[str, int] = Field(init=False)  # (1)!131 132          x: int133 134          model_config = ConfigDict(extra='allow')135 136 137      try:138          Model(x=1, y='a')139      except ValidationError as exc:140          print(exc)141          """142          1 validation error for Model143          y144            Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]145          """146 147      m = Model(x=1, y='2')148      assert m.x == 1149      assert m.y == 2150      assert m.model_dump() == {'x': 1, 'y': 2}151      assert m.__pydantic_extra__ == {'y': 2}152      ```153 154        1. The `= Field(init=False)` does not have any effect at runtime, but prevents the `__pydantic_extra__` field from155           being included as a parameter to the model's `__init__` method by type checkers.156 157    As well as specifying an `extra` configuration value on the model, you can also provide it as an argument to the validation methods.158    This will override any `extra` configuration value set on the model:159    ```python160    from pydantic import BaseModel, ConfigDict, ValidationError161 162    class Model(BaseModel):163        x: int164        model_config = ConfigDict(extra="allow")165 166    try:167        # Override model config and forbid extra fields just this time168        Model.model_validate({"x": 1, "y": 2}, extra="forbid")169    except ValidationError as exc:170        print(exc)171        """172        1 validation error for Model173        y174          Extra inputs are not permitted [type=extra_forbidden, input_value=2, input_type=int]175        """176    ```177    '''178 179    frozen: bool180    """181    Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates182    a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the183    attributes are hashable. Defaults to `False`.184 185    Note:186        On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.187    """188 189    populate_by_name: bool190    """191    Whether an aliased field may be populated by its name as given by the model192    attribute, as well as the alias. Defaults to `False`.193 194    !!! warning195        `populate_by_name` usage is not recommended in v2.11+ and will be deprecated in v3.196        Instead, you should use the [`validate_by_name`][pydantic.config.ConfigDict.validate_by_name] configuration setting.197 198        When `validate_by_name=True` and `validate_by_alias=True`, this is strictly equivalent to the199        previous behavior of `populate_by_name=True`.200 201        In v2.11, we also introduced a [`validate_by_alias`][pydantic.config.ConfigDict.validate_by_alias] setting that introduces more fine grained202        control for validation behavior.203 204        Here's how you might go about using the new settings to achieve the same behavior:205 206        ```python207        from pydantic import BaseModel, ConfigDict, Field208 209        class Model(BaseModel):210            model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)211 212            my_field: str = Field(alias='my_alias')  # (1)!213 214        m = Model(my_alias='foo')  # (2)!215        print(m)216        #> my_field='foo'217 218        m = Model(my_field='foo')  # (3)!219        print(m)220        #> my_field='foo'221        ```222 223        1. The field `'my_field'` has an alias `'my_alias'`.224        2. The model is populated by the alias `'my_alias'`.225        3. The model is populated by the attribute name `'my_field'`.226    """227 228    use_enum_values: bool229    """230    Whether to populate models with the `value` property of enums, rather than the raw enum.231    This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`.232 233    !!! note234        If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True`235        for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an236        enum's value occurs during validation, not serialization.237 238    ```python239    from enum import Enum240    from typing import Optional241 242    from pydantic import BaseModel, ConfigDict, Field243 244    class SomeEnum(Enum):245        FOO = 'foo'246        BAR = 'bar'247        BAZ = 'baz'248 249    class SomeModel(BaseModel):250        model_config = ConfigDict(use_enum_values=True)251 252        some_enum: SomeEnum253        another_enum: Optional[SomeEnum] = Field(254            default=SomeEnum.FOO, validate_default=True255        )256 257    model1 = SomeModel(some_enum=SomeEnum.BAR)258    print(model1.model_dump())259    #> {'some_enum': 'bar', 'another_enum': 'foo'}260 261    model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)262    print(model2.model_dump())263    #> {'some_enum': 'bar', 'another_enum': 'baz'}264    ```265    """266 267    validate_assignment: bool268    """269    Whether to validate the data when the model is changed. Defaults to `False`.270 271    The default behavior of Pydantic is to validate the data when the model is created.272 273    In case the user changes the data after the model is created, the model is _not_ revalidated.274 275    ```python276    from pydantic import BaseModel277 278    class User(BaseModel):279        name: str280 281    user = User(name='John Doe')  # (1)!282    print(user)283    #> name='John Doe'284    user.name = 123  # (1)!285    print(user)286    #> name=123287    ```288 289    1. The validation happens only when the model is created.290    2. The validation does not happen when the data is changed.291 292    In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:293 294    ```python295    from pydantic import BaseModel, ValidationError296 297    class User(BaseModel, validate_assignment=True):  # (1)!298        name: str299 300    user = User(name='John Doe')  # (2)!301    print(user)302    #> name='John Doe'303    try:304        user.name = 123  # (3)!305    except ValidationError as e:306        print(e)307        '''308        1 validation error for User309        name310          Input should be a valid string [type=string_type, input_value=123, input_type=int]311        '''312    ```313 314    1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`.315    2. The validation happens when the model is created.316    3. The validation _also_ happens when the data is changed.317    """318 319    arbitrary_types_allowed: bool320    """321    Whether arbitrary types are allowed for field types. Defaults to `False`.322 323    ```python324    from pydantic import BaseModel, ConfigDict, ValidationError325 326    # This is not a pydantic model, it's an arbitrary class327    class Pet:328        def __init__(self, name: str):329            self.name = name330 331    class Model(BaseModel):332        model_config = ConfigDict(arbitrary_types_allowed=True)333 334        pet: Pet335        owner: str336 337    pet = Pet(name='Hedwig')338    # A simple check of instance type is used to validate the data339    model = Model(owner='Harry', pet=pet)340    print(model)341    #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'342    print(model.pet)343    #> <__main__.Pet object at 0x0123456789ab>344    print(model.pet.name)345    #> Hedwig346    print(type(model.pet))347    #> <class '__main__.Pet'>348    try:349        # If the value is not an instance of the type, it's invalid350        Model(owner='Harry', pet='Hedwig')351    except ValidationError as e:352        print(e)353        '''354        1 validation error for Model355        pet356          Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]357        '''358 359    # Nothing in the instance of the arbitrary type is checked360    # Here name probably should have been a str, but it's not validated361    pet2 = Pet(name=42)362    model2 = Model(owner='Harry', pet=pet2)363    print(model2)364    #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'365    print(model2.pet)366    #> <__main__.Pet object at 0x0123456789ab>367    print(model2.pet.name)368    #> 42369    print(type(model2.pet))370    #> <class '__main__.Pet'>371    ```372    """373 374    from_attributes: bool375    """376    Whether to build models and look up discriminators of tagged unions using python object attributes.377    """378 379    loc_by_alias: bool380    """Whether to use the actual key provided in the data (e.g. alias) for error `loc`s rather than the field's name. Defaults to `True`."""381 382    alias_generator: Callable[[str], str] | AliasGenerator | None383    """384    A callable that takes a field name and returns an alias for it385    or an instance of [`AliasGenerator`][pydantic.aliases.AliasGenerator]. Defaults to `None`.386 387    When using a callable, the alias generator is used for both validation and serialization.388    If you want to use different alias generators for validation and serialization, you can use389    [`AliasGenerator`][pydantic.aliases.AliasGenerator] instead.390 391    If data source field names do not match your code style (e.g. CamelCase fields),392    you can automatically generate aliases using `alias_generator`. Here's an example with393    a basic callable:394 395    ```python396    from pydantic import BaseModel, ConfigDict397    from pydantic.alias_generators import to_pascal398 399    class Voice(BaseModel):400        model_config = ConfigDict(alias_generator=to_pascal)401 402        name: str403        language_code: str404 405    voice = Voice(Name='Filiz', LanguageCode='tr-TR')406    print(voice.language_code)407    #> tr-TR408    print(voice.model_dump(by_alias=True))409    #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}410    ```411 412    If you want to use different alias generators for validation and serialization, you can use413    [`AliasGenerator`][pydantic.aliases.AliasGenerator].414 415    ```python416    from pydantic import AliasGenerator, BaseModel, ConfigDict417    from pydantic.alias_generators import to_camel, to_pascal418 419    class Athlete(BaseModel):420        first_name: str421        last_name: str422        sport: str423 424        model_config = ConfigDict(425            alias_generator=AliasGenerator(426                validation_alias=to_camel,427                serialization_alias=to_pascal,428            )429        )430 431    athlete = Athlete(firstName='John', lastName='Doe', sport='track')432    print(athlete.model_dump(by_alias=True))433    #> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}434    ```435 436    Note:437        Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal],438        [`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake].439    """440 441    ignored_types: tuple[type, ...]442    """A tuple of types that may occur as values of class attributes without annotations. This is443    typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a444    class without an annotation and has a type that is not in this tuple (or otherwise recognized by445    _pydantic_), an error will be raised. Defaults to `()`.446    """447 448    allow_inf_nan: bool449    """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float and decimal fields. Defaults to `True`."""450 451    json_schema_extra: JsonDict | JsonSchemaExtraCallable | None452    """A dict or callable to provide extra JSON schema properties. Defaults to `None`."""453 454    json_encoders: dict[type[object], JsonEncoder] | None455    """456    A `dict` of custom JSON encoders for specific types. Defaults to `None`.457 458    /// version-deprecated | v2459    This configuration option is a carryover from v1. We originally planned to remove it in v2 but didn't have a 1:1 replacement460    so we are keeping it for now. It is still deprecated and will likely be removed in the future.461    ///462    """463 464    # new in V2465    strict: bool466    """467    Whether strict validation is applied to all fields on the model.468 469    By default, Pydantic attempts to coerce values to the correct type, when possible.470 471    There are situations in which you may want to disable this behavior, and instead raise an error if a value's type472    does not match the field's type annotation.473 474    To configure strict mode for all fields on a model, you can set `strict=True` on the model.475 476    ```python477    from pydantic import BaseModel, ConfigDict478 479    class Model(BaseModel):480        model_config = ConfigDict(strict=True)481 482        name: str483        age: int484    ```485 486    See [Strict Mode](../concepts/strict_mode.md) for more details.487 488    See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both489    strict and lax modes.490 491    /// version-added | v2492    ///493    """494    # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'495    revalidate_instances: Literal['always', 'never', 'subclass-instances']496    """497    When and how to revalidate models and dataclasses during validation. Can be one of:498 499    - `'never'`: will *not* revalidate models and dataclasses during validation500    - `'always'`: will revalidate models and dataclasses during validation501    - `'subclass-instances'`: will revalidate models and dataclasses during validation if the instance is a502        subclass of the model or dataclass503 504    The default is `'never'` (no revalidation).505 506    This configuration only affects *the current model* it is applied on, and does *not* propagate to the models507    referenced in fields.508 509    ```python510    from pydantic import BaseModel511 512    class User(BaseModel, revalidate_instances='never'):  # (1)!513        name: str514 515    class Transaction(BaseModel):516        user: User517 518    my_user = User(name='John')519    t = Transaction(user=my_user)520 521    my_user.name = 1  # (2)!522    t = Transaction(user=my_user)  # (3)!523    print(t)524    #> user=User(name=1)525    ```526 527    1. This is the default behavior.528    2. The assignment is *not* validated, unless you set [`validate_assignment`][pydantic.ConfigDict.validate_assignment] in the configuration.529    3. Since `revalidate_instances` is set to `'never'`, the user instance is not revalidated.530 531    Here is an example demonstrating the behavior of `'subclass-instances'`:532 533    ```python534    from pydantic import BaseModel535 536    class User(BaseModel, revalidate_instances='subclass-instances'):537        name: str538 539    class SubUser(User):540        age: int541 542    class Transaction(BaseModel):543        user: User544 545    my_user = User(name='John')546    my_user.name = 1  # (1)!547    t = Transaction(user=my_user)  # (2)!548    print(t)549    #> user=User(name=1)550 551    my_sub_user = SubUser(name='John', age=20)552    t = Transaction(user=my_sub_user)553    print(t)  # (3)!554    #> user=User(name='John')555    ```556 557    1. The assignment is *not* validated, unless you set [`validate_assignment`][pydantic.ConfigDict.validate_assignment] in the configuration.558    2. Because `my_user` is a "direct" instance of `User`, it is *not* being revalidated. It would have been the case if559      `revalidate_instances` was set to `'always'`.560    3. Because `my_sub_user` is an instance of a `User` subclass, it is being revalidated. In this case, Pydantic coerces `my_sub_user` to the defined561       `User` class defined on `Transaction`. If one of its fields had an invalid value, a validation error would have been raised.562 563    /// version-added | v2564    ///565    """566 567    ser_json_timedelta: Literal['iso8601', 'float']568    """569    The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and570    `'float'`. Defaults to `'iso8601'`.571 572    - `'iso8601'` will serialize timedeltas to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).573    - `'float'` will serialize timedeltas to the total number of seconds.574 575    /// version-changed | v2.12576    It is now recommended to use the [`ser_json_temporal`][pydantic.config.ConfigDict.ser_json_temporal]577    setting. `ser_json_timedelta` will be deprecated in v3.578    ///579    """580 581    ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds']582    """583    The format of JSON serialized temporal types from the [`datetime`][] module. This includes:584 585    - [`datetime.datetime`][]586    - [`datetime.date`][]587    - [`datetime.time`][]588    - [`datetime.timedelta`][]589 590    Can be one of:591 592    - `'iso8601'` will serialize date-like types to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).593    - `'milliseconds'` will serialize date-like types to a floating point number of milliseconds since the epoch.594    - `'seconds'` will serialize date-like types to a floating point number of seconds since the epoch.595 596    Defaults to `'iso8601'`.597 598    /// version-added | v2.12599    This setting replaces [`ser_json_timedelta`][pydantic.config.ConfigDict.ser_json_timedelta],600    which will be deprecated in v3. `ser_json_temporal` adds more configurability for the other temporal types.601    ///602    """603 604    val_temporal_unit: Literal['seconds', 'milliseconds', 'infer']605    """606    The unit to assume for validating numeric input for datetime-like types ([`datetime.datetime`][] and [`datetime.date`][]). Can be one of:607 608    - `'seconds'` will validate date or time numeric inputs as seconds since the [epoch].609    - `'milliseconds'` will validate date or time numeric inputs as milliseconds since the [epoch].610    - `'infer'` will infer the unit from the string numeric input on unix time as:611 612        * seconds since the [epoch] if $-2^{10} <= v <= 2^{10}$613        * milliseconds since the [epoch] (if $v < -2^{10}$ or $v > 2^{10}$).614 615    Defaults to `'infer'`.616 617    /// version-added | v2.12618    ///619 620    [epoch]: https://en.wikipedia.org/wiki/Unix_time621    """622 623    ser_json_bytes: Literal['utf8', 'base64', 'hex']624    """625    The encoding of JSON serialized bytes. Defaults to `'utf8'`.626    Set equal to `val_json_bytes` to get back an equal value after serialization round trip.627 628    - `'utf8'` will serialize bytes to UTF-8 strings.629    - `'base64'` will serialize bytes to URL safe base64 strings.630    - `'hex'` will serialize bytes to hexadecimal strings.631    """632 633    val_json_bytes: Literal['utf8', 'base64', 'hex']634    """635    /// version-added | v2.9636    ///637 638    The encoding of JSON serialized bytes to decode. Defaults to `'utf8'`.639    Set equal to `ser_json_bytes` to get back an equal value after serialization round trip.640 641    - `'utf8'` will deserialize UTF-8 strings to bytes.642    - `'base64'` will deserialize URL safe base64 strings to bytes.643    - `'hex'` will deserialize hexadecimal strings to bytes.644    """645 646    ser_json_inf_nan: Literal['null', 'constants', 'strings']647    """648    The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`.649 650    - `'null'` will serialize infinity and NaN values as `null`.651    - `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`.652    - `'strings'` will serialize infinity as string `"Infinity"` and NaN as string `"NaN"`.653    """654 655    # whether to validate default values during validation, default False656    validate_default: bool657    """Whether to validate default values during validation. Defaults to `False`."""658 659    validate_return: bool660    """Whether to validate the return value from call validators. Defaults to `False`."""661 662    protected_namespaces: tuple[str | Pattern[str], ...]663    """664    A tuple of strings and/or regex patterns that prevent models from having fields with names that conflict with its existing members/methods.665 666    Strings are matched on a prefix basis. For instance, with `'dog'`, having a field named `'dog_name'` will be disallowed.667 668    Regex patterns are matched on the entire field name. For instance, with the pattern `'^dog$'`, having a field named `'dog'` will be disallowed,669    but `'dog_name'` will be accepted.670 671    Defaults to `('model_validate', 'model_dump')`. This default is used to prevent collisions with the existing (and possibly future)672    [validation](../concepts/models.md#validating-data) and [serialization](../concepts/serialization.md#serializing-data) methods.673 674    ```python675    import warnings676 677    from pydantic import BaseModel678 679    warnings.filterwarnings('error')  # Raise warnings as errors680 681    try:682 683        class Model(BaseModel):684            model_dump_something: str685 686    except UserWarning as e:687        print(e)688        '''689        Field 'model_dump_something' in 'Model' conflicts with protected namespace 'model_dump'.690 691        You may be able to solve this by setting the 'protected_namespaces' configuration to ('model_validate',).692        '''693    ```694 695    You can customize this behavior using the `protected_namespaces` setting:696 697    ```python {test="skip"}698    import re699    import warnings700 701    from pydantic import BaseModel, ConfigDict702 703    with warnings.catch_warnings(record=True) as caught_warnings:704        warnings.simplefilter('always')  # Catch all warnings705 706        class Model(BaseModel):707            safe_field: str708            also_protect_field: str709            protect_this: str710 711            model_config = ConfigDict(712                protected_namespaces=(713                    'protect_me_',714                    'also_protect_',715                    re.compile('^protect_this$'),716                )717            )718 719    for warning in caught_warnings:720        print(f'{warning.message}')721        '''722        Field 'also_protect_field' in 'Model' conflicts with protected namespace 'also_protect_'.723        You may be able to solve this by setting the 'protected_namespaces' configuration to ('protect_me_', re.compile('^protect_this$'))`.724 725        Field 'protect_this' in 'Model' conflicts with protected namespace 're.compile('^protect_this$')'.726        You may be able to solve this by setting the 'protected_namespaces' configuration to ('protect_me_', 'also_protect_')`.727        '''728    ```729 730    While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,731    an error _is_ raised if there is an actual collision with an existing attribute:732 733    ```python734    from pydantic import BaseModel, ConfigDict735 736    try:737 738        class Model(BaseModel):739            model_validate: str740 741            model_config = ConfigDict(protected_namespaces=('model_',))742 743    except ValueError as e:744        print(e)745        '''746        Field 'model_validate' conflicts with member <bound method BaseModel.model_validate of <class 'pydantic.main.BaseModel'>> of protected namespace 'model_'.747        '''748    ```749 750    /// version-changed | v2.10751    The default protected namespaces was changed from `('model_',)` to `('model_validate', 'model_dump')`, to allow752    for fields like `model_id`, `model_name` to be used.753    ///754    """755 756    hide_input_in_errors: bool757    """758    Whether to hide inputs when printing errors. Defaults to `False`.759 760    Pydantic shows the input value and type when it raises `ValidationError` during the validation.761 762    ```python763    from pydantic import BaseModel, ValidationError764 765    class Model(BaseModel):766        a: str767 768    try:769        Model(a=123)770    except ValidationError as e:771        print(e)772        '''773        1 validation error for Model774        a775          Input should be a valid string [type=string_type, input_value=123, input_type=int]776        '''777    ```778 779    You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.780 781    ```python782    from pydantic import BaseModel, ConfigDict, ValidationError783 784    class Model(BaseModel):785        a: str786        model_config = ConfigDict(hide_input_in_errors=True)787 788    try:789        Model(a=123)790    except ValidationError as e:791        print(e)792        '''793        1 validation error for Model794        a795          Input should be a valid string [type=string_type]796        '''797    ```798    """799 800    defer_build: bool801    """802    Whether to defer model validator and serializer construction until the first model validation. Defaults to False.803 804    This can be useful to avoid the overhead of building models which are only805    used nested within other models, or when you want to manually define type namespace via806    [`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild].807 808    /// version-changed | v2.10809    The setting also applies to [Pydantic dataclasses](../concepts/dataclasses.md) and [type adapters](../concepts/type_adapter.md).810    ///811    """812 813    plugin_settings: dict[str, object] | None814    """A `dict` of settings for plugins. Defaults to `None`."""815 816    schema_generator: type[_GenerateSchema] | None817    """818    The `GenerateSchema` class to use during core schema generation.819 820    /// version-deprecated | v2.10821    The `GenerateSchema` class is private and highly subject to change.822    ///823    """824 825    json_schema_serialization_defaults_required: bool826    """827    Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`.828 829    This ensures that the serialization schema will reflect the fact a field with a default will always be present830    when serializing the model, even though it is not required for validation.831 832    However, there are scenarios where this may be undesirable — in particular, if you want to share the schema833    between validation and serialization, and don't mind fields with defaults being marked as not required during834    serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.835 836    ```python837    from pydantic import BaseModel, ConfigDict838 839    class Model(BaseModel):840        a: str = 'a'841 842        model_config = ConfigDict(json_schema_serialization_defaults_required=True)843 844    print(Model.model_json_schema(mode='validation'))845    '''846    {847        'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},848        'title': 'Model',849        'type': 'object',850    }851    '''852    print(Model.model_json_schema(mode='serialization'))853    '''854    {855        'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},856        'required': ['a'],857        'title': 'Model',858        'type': 'object',859    }860    '''861    ```862 863    /// version-added | v2.4864    ///865    """866 867    json_schema_mode_override: Literal['validation', 'serialization', None]868    """869    If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to870    the function call. Defaults to `None`.871 872    This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the873    validation schema.874 875    It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation876    and serialization that must both be referenced from the same schema; when this happens, we automatically append877    `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the878    serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between879    the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes880    from being added to the definition references.881 882    ```python883    from pydantic import BaseModel, ConfigDict, Json884 885    class Model(BaseModel):886        a: Json[int]  # requires a string to validate, but will dump an int887 888    print(Model.model_json_schema(mode='serialization'))889    '''890    {891        'properties': {'a': {'title': 'A', 'type': 'integer'}},892        'required': ['a'],893        'title': 'Model',894        'type': 'object',895    }896    '''897 898    class ForceInputModel(Model):899        # the following ensures that even with mode='serialization', we900        # will get the schema that would be generated for validation.901        model_config = ConfigDict(json_schema_mode_override='validation')902 903    print(ForceInputModel.model_json_schema(mode='serialization'))904    '''905    {906        'properties': {907            'a': {908                'contentMediaType': 'application/json',909                'contentSchema': {'type': 'integer'},910                'title': 'A',911                'type': 'string',912            }913        },914        'required': ['a'],915        'title': 'ForceInputModel',916        'type': 'object',917    }918    '''919    ```920 921    /// version-added | v2.4922    ///923    """924 925    coerce_numbers_to_str: bool926    """927    If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`.928 929    Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.930 931    ```python932    from decimal import Decimal933 934    from pydantic import BaseModel, ConfigDict, ValidationError935 936    class Model(BaseModel):937        value: str938 939    try:940        print(Model(value=42))941    except ValidationError as e:942        print(e)943        '''944        1 validation error for Model945        value946          Input should be a valid string [type=string_type, input_value=42, input_type=int]947        '''948 949    class Model(BaseModel):950        model_config = ConfigDict(coerce_numbers_to_str=True)951 952        value: str953 954    repr(Model(value=42).value)955    #> "42"956    repr(Model(value=42.13).value)957    #> "42.13"958    repr(Model(value=Decimal('42.13')).value)959    #> "42.13"960    ```961    """962 963    regex_engine: Literal['rust-regex', 'python-re']964    """965    The regex engine to be used for pattern validation.966    Defaults to `'rust-regex'`.967 968    - `'rust-regex'` uses the [`regex`](https://docs.rs/regex) Rust crate,969      which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.970    - `'python-re'` use the [`re`][] module, which supports all regex features, but may be slower.971 972    !!! note973        If you use a compiled regex pattern, the `'python-re'` engine will be used regardless of this setting.974        This is so that flags such as [`re.IGNORECASE`][] are respected.975 976    ```python977    from pydantic import BaseModel, ConfigDict, Field, ValidationError978 979    class Model(BaseModel):980        model_config = ConfigDict(regex_engine='python-re')981 982        value: str = Field(pattern=r'^abc(?=def)')983 984    print(Model(value='abcdef').value)985    #> abcdef986 987    try:988        print(Model(value='abxyzcdef'))989    except ValidationError as e:990        print(e)991        '''992        1 validation error for Model993        value994          String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]995        '''996    ```997 998    /// version-added | v2.5999    ///1000    """1001 1002    validation_error_cause: bool1003    """1004    If `True`, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to `False`.1005 1006    Note:1007        Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.1008 1009    Note:1010        The structure of validation errors are likely to change in future Pydantic versions. Pydantic offers no guarantees about their structure. Should be used for visual traceback debugging only.1011 1012    /// version-added | v2.51013    ///1014    """1015 1016    use_attribute_docstrings: bool1017    '''1018    Whether docstrings of attributes (bare string literals immediately following the attribute declaration)1019    should be used for field descriptions. Defaults to `False`.1020 1021    ```python1022    from pydantic import BaseModel, ConfigDict, Field1023 1024 1025    class Model(BaseModel):1026        model_config = ConfigDict(use_attribute_docstrings=True)1027 1028        x: str1029        """1030        Example of an attribute docstring1031        """1032 1033        y: int = Field(description="Description in Field")1034        """1035        Description in Field overrides attribute docstring1036        """1037 1038 1039    print(Model.model_fields["x"].description)1040    # > Example of an attribute docstring1041    print(Model.model_fields["y"].description)1042    # > Description in Field1043    ```1044    This requires the source code of the class to be available at runtime (and so won't work in the interactive interpreter shell).1045 1046    !!! warning "Usage with `TypedDict` and stdlib dataclasses"1047        Due to current limitations, attribute docstrings detection may not work as expected when using1048        [`TypedDict`][typing.TypedDict] and stdlib dataclasses, in particular when:1049 1050        - inheritance is being used.1051        - multiple classes have the same name in the same source file (unless Python 3.13 or greater is used).1052 1053    /// version-added | v2.71054    ///1055    '''1056 1057    cache_strings: bool | Literal['all', 'keys', 'none']1058    """1059    Whether to cache strings to avoid constructing new Python objects. Defaults to True.1060 1061    Enabling this setting should significantly improve validation performance while increasing memory usage slightly.1062 1063    - `True` or `'all'` (the default): cache all strings1064    - `'keys'`: cache only dictionary keys1065    - `False` or `'none'`: no caching1066 1067    !!! note1068        `True` or `'all'` is required to cache strings during general validation because1069        validators don't know if they're in a key or a value.1070 1071    !!! tip1072        If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage,1073        as the performance difference is minimal if repeated strings are rare.1074 1075    /// version-added | v2.71076    ///1077    """1078 1079    validate_by_alias: bool1080    """1081    Whether an aliased field may be populated by its alias. Defaults to `True`.1082 1083    Here's an example of disabling validation by alias:1084 1085    ```py1086    from pydantic import BaseModel, ConfigDict, Field1087 1088    class Model(BaseModel):1089        model_config = ConfigDict(validate_by_name=True, validate_by_alias=False)1090 1091        my_field: str = Field(validation_alias='my_alias')  # (1)!1092 1093    m = Model(my_field='foo')  # (2)!1094    print(m)1095    #> my_field='foo'1096    ```1097 1098    1. The field `'my_field'` has an alias `'my_alias'`.1099    2. The model can only be populated by the attribute name `'my_field'`.1100 1101    !!! warning1102        You cannot set both `validate_by_alias` and `validate_by_name` to `False`.1103        This would make it impossible to populate an attribute.1104 1105        See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.1106 1107        If you set `validate_by_alias` to `False`, under the hood, Pydantic dynamically sets1108        `validate_by_name` to `True` to ensure that validation can still occur.1109 1110    /// version-added | v2.111111    This setting was introduced in conjunction with [`validate_by_name`][pydantic.ConfigDict.validate_by_name]1112    to empower users with more fine grained validation control.1113    ///1114    """1115 1116    validate_by_name: bool1117    """1118    Whether an aliased field may be populated by its name as given by the model1119    attribute. Defaults to `False`.1120 1121    ```python1122    from pydantic import BaseModel, ConfigDict, Field1123 1124    class Model(BaseModel):1125        model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)1126 1127        my_field: str = Field(validation_alias='my_alias')  # (1)!1128 1129    m = Model(my_alias='foo')  # (2)!1130    print(m)1131    #> my_field='foo'1132 1133    m = Model(my_field='foo')  # (3)!1134    print(m)1135    #> my_field='foo'1136    ```1137 1138    1. The field `'my_field'` has an alias `'my_alias'`.1139    2. The model is populated by the alias `'my_alias'`.1140    3. The model is populated by the attribute name `'my_field'`.1141 1142    !!! warning1143        You cannot set both `validate_by_alias` and `validate_by_name` to `False`.1144        This would make it impossible to populate an attribute.1145 1146        See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.1147 1148    /// version-added | v2.111149    This setting was introduced in conjunction with [`validate_by_alias`][pydantic.ConfigDict.validate_by_alias]1150    to empower users with more fine grained validation control. It is an alternative to [`populate_by_name`][pydantic.ConfigDict.populate_by_name],1151    that enables validation by name **and** by alias.1152    ///1153    """1154 1155    serialize_by_alias: bool1156    """1157    Whether an aliased field should be serialized by its alias. Defaults to `False`.1158 1159    Note: In v2.11, `serialize_by_alias` was introduced to address the1160    [popular request](https://github.com/pydantic/pydantic/issues/8379)1161    for consistency with alias behavior for validation and serialization settings.1162    In v3, the default value is expected to change to `True` for consistency with the validation default.1163 1164    ```python1165    from pydantic import BaseModel, ConfigDict, Field1166 1167    class Model(BaseModel):1168        model_config = ConfigDict(serialize_by_alias=True)1169 1170        my_field: str = Field(serialization_alias='my_alias')  # (1)!1171 1172    m = Model(my_field='foo')1173    print(m.model_dump())  # (2)!1174    #> {'my_alias': 'foo'}1175    ```1176 1177    1. The field `'my_field'` has an alias `'my_alias'`.1178    2. The model is serialized using the alias `'my_alias'` for the `'my_field'` attribute.1179 1180 1181    /// version-added | v2.111182    This setting was introduced to address the [popular request](https://github.com/pydantic/pydantic/issues/8379)1183    for consistency with alias behavior for validation and serialization.1184 1185    In v3, the default value is expected to change to `True` for consistency with the validation default.1186    ///1187    """1188 1189    url_preserve_empty_path: bool1190    """1191    Whether to preserve empty URL paths when validating values for a URL type. Defaults to `False`.1192 1193    ```python1194    from pydantic import AnyUrl, BaseModel, ConfigDict1195 1196    class Model(BaseModel):1197        model_config = ConfigDict(url_preserve_empty_path=True)1198 1199        url: AnyUrl1200 

Showing the first 1,200 of 1297 lines. Download the file for the rest.

codekingpro/portable-devtools · Team Ai