### Clone Pydantic Repository and Setup Environment (Shell) Source: https://docs.pydantic.dev/2.12/contributing This set of commands clones the Pydantic repository, installs necessary tools like uv and pre-commit, and sets up the project dependencies and test environment using make. It requires git, pipx, and make to be installed. ```shell # Clone your fork and cd into the repo directory git clone git@github.com:/pydantic.git cd pydantic # Install UV and pre-commit # We use pipx here, for other options see: # https://docs.astral.sh/uv/getting-started/installation/ # https://pre-commit.com/#install # To get pipx itself: # https://pypa.github.io/pipx/ pipx install uv pipx install pre-commit # Install pydantic, dependencies, test dependencies and doc dependencies make install ``` -------------------------------- ### Install Pydantic V2 Source: https://docs.pydantic.dev/2.12/migration Installs the latest version of Pydantic V2 from PyPI using pip. This is the recommended command for users starting with Pydantic V2 or migrating existing projects. ```bash pip install -U pydantic ``` -------------------------------- ### Updating Documentation Code Examples with Pytest (Python) Source: https://docs.pydantic.dev/2.12/contributing Shows the command to run Pytest to test and update code examples within the Pydantic documentation. This ensures that all code examples are correct and runnable. ```python # Run tests and update code examples pytest tests/test_docs.py --update-examples ``` -------------------------------- ### Install Pydantic V1 Source: https://docs.pydantic.dev/2.12/migration Installs a specific version of Pydantic V1 using pip. This command is useful if you need to maintain compatibility with Pydantic V1 or require specific V1 features during a migration phase. ```bash pip install "pydantic==1.*" ``` -------------------------------- ### Install Bump Pydantic Code Transformation Tool Source: https://docs.pydantic.dev/2.12/migration Installs the 'bump-pydantic' tool, a beta utility designed to assist in automatically migrating Pydantic V1 code to Pydantic V2 syntax. This tool simplifies the process of updating imports and code structures. ```bash pip install bump-pydantic ``` -------------------------------- ### Install Pydantic Settings Source: https://docs.pydantic.dev/2.12/concepts/pydantic_settings Installs the pydantic-settings library using pip. This is the first step to using Pydantic's settings management features. ```bash pip install pydantic-settings ``` -------------------------------- ### Install datamodel-code-generator Source: https://docs.pydantic.dev/2.12/integrations/datamodel_code_generator Installs the datamodel-code-generator library using pip. This is the first step to using the tool for generating pydantic models. ```shell pip install datamodel-code-generator ``` -------------------------------- ### ArgsKwargs Usage Example with Pydantic Dataclasses Source: https://docs.pydantic.dev/2.12/api/pydantic_core Illustrates how ArgsKwargs is used when creating Pydantic dataclass instances, showing how positional and keyword arguments are captured. ```python from pydantic.dataclasses import dataclass from pydantic import model_validator @dataclass class Model: a: int b: int @model_validator(mode="before") @classmethod def no_op_validator(cls, values): print(values) return values Model(1, b=2) # > ArgsKwargs((1,), {"b": 2}) Model(1, 2) # > ArgsKwargs((1, 2), {}) Model(a=1, b=2) # > ArgsKwargs((), {"a": 1, "b": 2}) ``` -------------------------------- ### Pydantic PostgresDsn Model Example Source: https://docs.pydantic.dev/2.12/api/networks Demonstrates the basic usage of `PostgresDsn` within a Pydantic `BaseModel`. While the example focuses on `HttpUrl` for simplicity, it indicates where `PostgresDsn` would be used for validating PostgreSQL connection strings. `PostgresDsn` requires user info, host, and supports multiple hosts, with TLD not being required. ```python from pydantic import ( BaseModel, HttpUrl, PostgresDsn, ValidationError, field_validator, ) class MyModel(BaseModel): url: HttpUrl m = MyModel(url='http://www.example.com') ``` -------------------------------- ### Pydantic constr: Basic String Constraints Example (Python) Source: https://docs.pydantic.dev/2.12/api/types Provides a basic example of using Pydantic's `constr` function to apply string constraints, specifically whitespace stripping and case conversion. It demonstrates how to instantiate a model with a string value and shows the resulting transformed output. ```python from pydantic import BaseModel, constr class Foo(BaseModel): bar: constr(strip_whitespace=True, to_upper=True) foo = Foo(bar=' hello ') print(foo) #> bar='HELLO' ``` -------------------------------- ### Configure TypeAdapter with ConfigDict Source: https://docs.pydantic.dev/2.12/concepts/config Demonstrates how to configure a `TypeAdapter` by providing a `ConfigDict` to the `config` argument. This example configures the adapter to coerce numbers to strings when validating a list of strings. ```python from pydantic import ConfigDict, TypeAdapter ta = TypeAdapter(list[str], config=ConfigDict(coerce_numbers_to_str=True)) print(ta.validate_python([1, 2])) ``` -------------------------------- ### Build Documentation (Make) Source: https://docs.pydantic.dev/2.12/contributing This command builds the project's documentation using mkdocs-material. It's crucial to run this after making documentation changes to ensure they render correctly. The documentation can also be served locally using `uv run mkdocs serve`. ```make # Build documentation make docs # If you have changed the documentation, make sure it builds successfully. # You can also use `uv run mkdocs serve` to serve the documentation at localhost:8000 ``` -------------------------------- ### Get Pydantic Version Info (Python < 2.0) Source: https://docs.pydantic.dev/2.12/contributing This snippet retrieves the Pydantic version information for versions prior to v2.0. It's useful for debugging and ensuring compatibility when reporting issues with older Pydantic installations. It requires the Pydantic library to be installed. ```python import pydantic.utils print(pydantic.utils.version_info()) ``` -------------------------------- ### Initialize Settings Source with Keyword Arguments (Python) Source: https://docs.pydantic.dev/2.12/api/pydantic_settings The InitSettingsSource class loads configuration values provided directly during the initialization of a settings class. It accepts initialization keyword arguments and applies them as settings. This source is useful for providing default or overriding values programmatically. ```python def __init__( self, settings_cls: type[BaseSettings], init_kwargs: dict[str, Any], nested_model_default_partial_update: bool | None = None, ): self.init_kwargs = init_kwargs super().__init__(settings_cls) self.nested_model_default_partial_update = ( nested_model_default_partial_update if nested_model_default_partial_update is not None else self.config.get('nested_model_default_partial_update', False) ) ``` -------------------------------- ### Load multiple .env files with priority (Python) Source: https://docs.pydantic.dev/2.12/concepts/pydantic_settings This example demonstrates how to load multiple .env files by providing a tuple or list of filenames to the `env_file` configuration. Files are loaded in order, with later files overriding earlier ones, allowing for prioritized configuration. ```python from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict( # ".env.prod" takes priority over ".env" env_file=('.env', '.env.prod') ) ``` -------------------------------- ### Initialize CliSettingsSource in Python Source: https://docs.pydantic.dev/2.12/api/pydantic_settings This code snippet shows the constructor for the `CliSettingsSource` class in Pydantic. It outlines the various parameters available for configuring how settings are parsed from command-line arguments, including options for argument parsing, naming conventions, and error handling. Dependencies include the `pydantic.settings` module and potentially `argparse` for advanced customization. ```python CliSettingsSource( settings_cls: type[BaseSettings], cli_prog_name: str | None = None, cli_parse_args: ( bool | list[str] | tuple[str, ...] | None ) = None, cli_parse_none_str: str | None = None, cli_hide_none_type: bool | None = None, cli_avoid_json: bool | None = None, cli_enforce_required: bool | None = None, cli_use_class_docs_for_groups: bool | None = None, cli_exit_on_error: bool | None = None, cli_prefix: str | None = None, cli_flag_prefix_char: str | None = None, cli_implicit_flags: bool | None = None, cli_ignore_unknown_args: bool | None = None, cli_kebab_case: bool | None = None, case_sensitive: bool | None = True, root_parser: Any = None, parse_args_method: Callable[..., Any] | None = None, add_argument_method: ( Callable[..., Any] | None ) = add_argument, add_argument_group_method: ( Callable[..., Any] | None ) = add_argument_group, add_parser_method: ( Callable[..., Any] | None ) = add_parser, add_subparsers_method: ( Callable[..., Any] | None ) = add_subparsers, formatter_class: Any = RawDescriptionHelpFormatter, ) ``` -------------------------------- ### Pydantic Dynamic Model Creation with Advanced Field Definitions Source: https://docs.pydantic.dev/2.12/concepts/models Demonstrates advanced dynamic model creation using `create_model`, including field aliases, descriptions, and private attributes. It shows how these map to equivalent static model definitions. ```python from typing import Annotated from pydantic import BaseModel, Field, PrivateAttr, create_model DynamicModel = create_model( 'DynamicModel', foo=(str, Field(alias='FOO')), bar=Annotated[str, Field(description='Bar field')], _private=(int, PrivateAttr(default=1)), ) class StaticModel(BaseModel): foo: str = Field(alias='FOO') bar: Annotated[str, Field(description='Bar field')] _private: int = PrivateAttr(default=1) ``` -------------------------------- ### Pydantic V1 Deprecated Validator Example Source: https://docs.pydantic.dev/2.12/migration Demonstrates the usage of the deprecated `@validator` decorator with `always=True` in Pydantic V1, which could lead to unexpected behavior with default values. This example highlights a scenario that might raise a `ValidationError` in Pydantic V1 due to the interaction of `always=True` with default values. ```python from pydantic import BaseModel, validator class Model(BaseModel): x: str = 1 @validator('x', always=True) @classmethod def validate_x(cls, v): return v Model() ``` -------------------------------- ### Get Pydantic Version Info (Python 3.x) Source: https://docs.pydantic.dev/2.12/contributing This snippet retrieves the Pydantic version information. It's useful for debugging and ensuring compatibility when reporting issues. It requires the Pydantic library to be installed. ```python import pydantic.version print(pydantic.version.version_info()) ``` -------------------------------- ### Pydantic Dynamic Model Creation with create_model Source: https://docs.pydantic.dev/2.12/concepts/models Shows how to dynamically create Pydantic models using `create_model`. This example defines a model with basic type annotations and default values, equivalent to a statically defined model. ```python from pydantic import BaseModel, create_model DynamicFoobarModel = create_model('DynamicFoobarModel', foo=str, bar=(int, 123)) # Equivalent to: class StaticFoobarModel(BaseModel): foo: str bar: int = 123 ``` -------------------------------- ### Create Generic Pydantic HTTP Response Wrapper (Python 3.12+ New Syntax) Source: https://docs.pydantic.dev/2.12/concepts/models Illustrates creating a generic Pydantic model 'Response' using Python 3.12's new type parameter syntax. It mirrors the functionality of the older syntax, demonstrating instantiation and validation. Requires 'pydantic'. ```python from pydantic import BaseModel, ValidationError class DataModel(BaseModel): number: int class Response[DataT](BaseModel): data: DataT print(Response[int](data=1)) #> data=1 print(Response[str](data='value')) #> data='value' print(Response[str](data='value').model_dump()) #> {'data': 'value'} data = DataModel(number=1) print(Response[DataModel](data=data).model_dump()) #> {'data': {'number': 1}} try: Response[int](data='value') except ValidationError as e: print(e) """ 1 validation error for Response[int] data Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='value', input_type=str] """ ``` -------------------------------- ### Pydantic V2: Optional and Required Fields (Python 3.9+) Source: https://docs.pydantic.dev/2.12/migration Demonstrates how Pydantic V2 handles required, optional, and nullable fields using `typing.Optional`. It shows examples of valid and invalid data inputs and the resulting `ValidationError`. ```python from typing import Optional from pydantic import BaseModel, ValidationError class Foo(BaseModel): f1: str # required, cannot be None f2: Optional[str] # required, can be None - same as str | None f3: Optional[str] = None # not required, can be None f4: str = 'Foobar' # not required, but cannot be None try: Foo(f1=None, f2=None, f4='b') except ValidationError as e: print(e) """ 1 validation error for Foo f1 Input should be a valid string [type=string_type, input_value=None, input_type=NoneType] """ ``` -------------------------------- ### Modify Schema with Annotated Metadata: RestrictCharacters (Python) Source: https://docs.pydantic.dev/2.12/concepts/json_schema Illustrates using Annotated metadata with a custom type 'RestrictCharacters' to modify Pydantic's schema generation for strings. This example shows how to call the handler to get the base schema and then apply custom validation logic. ```python from collections.abc import Sequence from dataclasses import dataclass from typing import Annotated, Any from pydantic_core import core_schema from pydantic import BaseModel, GetCoreSchemaHandler, ValidationError @dataclass class RestrictCharacters: alphabet: Sequence[str] def __get_pydantic_core_schema__( self, source: type[Any], handler: GetCoreSchemaHandler ) -> core_schema.CoreSchema: if not self.alphabet: raise ValueError('Alphabet may not be empty') schema = handler( source ) # get the CoreSchema from the type / inner constraints if schema['type'] != 'str': raise TypeError('RestrictCharacters can only be applied to strings') return core_schema.no_info_after_validator_function( self.validate, schema, ) def validate(self, value: str) -> str: if any(c not in self.alphabet for c in value): raise ValueError( f'{value!r} is not restricted to {self.alphabet!r}' ) return value class MyModel(BaseModel): value: Annotated[str, RestrictCharacters('ABC')] print(MyModel.model_json_schema()) print(MyModel(value='CBA')) try: MyModel(value='XYZ') except ValidationError as e: print(e) ``` -------------------------------- ### Initialize TomlConfigSettingsSource (Python) Source: https://docs.pydantic.dev/2.12/api/pydantic_settings Initializes a source class for loading settings from a TOML file. It reads the TOML file content and sets up the configuration source. This class inherits from InitSettingsSource and ConfigFileSourceMixin. ```python def __init__( self, settings_cls: type[BaseSettings], toml_file: PathType | None = DEFAULT_PATH, ): self.toml_file_path = toml_file if toml_file != DEFAULT_PATH else settings_cls.model_config.get('toml_file') self.toml_data = self._read_files(self.toml_file_path) super().__init__(settings_cls, self.toml_data) ``` -------------------------------- ### Pydantic V2 Constrained Types Migration Source: https://docs.pydantic.dev/2.12/migration Illustrates the migration of Pydantic V1's `Constrained*` classes to Pydantic V2's `Annotated` with `Field`. This example shows how to replace `ConstrainedInt` with `Annotated[int, Field(ge=0)]` for defining constrained integer fields. ```python from typing import Annotated from pydantic import BaseModel, Field MyInt = Annotated[int, Field(ge=0)] class Model(BaseModel): x: MyInt ``` -------------------------------- ### TypeAdapter Initialization Source: https://docs.pydantic.dev/2.12/api/type_adapter Demonstrates how to initialize a TypeAdapter with a given type and optional configuration. ```APIDOC ## POST /typeadapter ### Description Initializes a `TypeAdapter` instance for flexible validation and serialization based on a Python type. ### Method POST ### Endpoint /typeadapter ### Parameters #### Query Parameters - **type** (Any) - Required - The type associated with the `TypeAdapter`. - **config** (ConfigDict | None) - Optional - Configuration for the `TypeAdapter`, should be a dictionary conforming to `ConfigDict`. Cannot be provided if the type has its own un-overridable config (e.g., `BaseModel`, `TypedDict`, `dataclass`). - **_parent_depth** (int) - Optional - Depth at which to search for the parent frame for resolving forward annotations. Defaults to 2. - **module** (str | None) - Optional - The module that passes to plugin if provided. ### Request Body This endpoint does not typically use a request body for initialization, parameters are passed as query parameters or directly in the constructor. ### Response #### Success Response (200) - **TypeAdapter instance** - A `TypeAdapter` instance configured with the specified type and options. #### Response Example ```json { "message": "TypeAdapter initialized successfully" } ``` ``` -------------------------------- ### Pydantic V2: Float to Integer Type Conversion Source: https://docs.pydantic.dev/2.12/migration Demonstrates Pydantic V2's stricter type conversion from floats to integers. Floats are only accepted if they have a zero decimal part, otherwise a `ValidationError` is raised. Shows successful conversion and an example of a validation error. ```python from pydantic import BaseModel, ValidationError class Model(BaseModel): x: int print(Model(x=10.0)) #> x=10 try: Model(x=10.2) except ValidationError as err: print(err) """ 1 validation error for Model x Input should be a valid integer, got a number with a fractional part [type=int_from_float, input_value=10.2, input_type=float] """ ``` -------------------------------- ### Pydantic V2: Optional and Required Fields (Python 3.10+) Source: https://docs.pydantic.dev/2.12/migration Illustrates Pydantic V2's field validation using the `|` union operator for optional and nullable fields, as introduced in Python 3.10. Includes examples of input data and expected validation errors. ```python from pydantic import BaseModel, ValidationError class Foo(BaseModel): f1: str # required, cannot be None f2: str | None # required, can be None - same as str | None f3: str | None = None # not required, can be None f4: str = 'Foobar' # not required, but cannot be None try: Foo(f1=None, f2=None, f4='b') except ValidationError as e: print(e) """ 1 validation error for Foo f1 Input should be a valid string [type=string_type, input_value=None, input_type=NoneType] """ ``` -------------------------------- ### Add Examples to JSON Schema with Examples Annotation Source: https://docs.pydantic.dev/2.12/api/json_schema The `Examples` annotation is used to add example data to a JSON schema. It can accept examples as a dictionary or a list. If the schema already has examples, the new ones are appended. This annotation also supports specifying different examples for validation and serialization modes. ```python def __init__( self, examples: dict[str, Any] | list[Any], mode: Literal['validation', 'serialization'] | None = None ) -> None: if isinstance(examples, dict): warnings.warn( 'Using a dict for `examples` is deprecated, use a list instead.', PydanticDeprecatedSince29, stacklevel=2, ) self.examples = examples self.mode = mode ``` -------------------------------- ### JSON Serialization of None Keys in Pydantic V1 and V2 Source: https://docs.pydantic.dev/2.12/migration Demonstrates the difference in JSON serialization for dictionary keys that are `None` between Pydantic V1 and V2. Pydantic V1 serializes `None` keys as 'null', while Pydantic V2 maintains this behavior. This example uses `BaseModel` from both versions to illustrate the output. ```python from typing import Optional from pydantic import BaseModel as V2BaseModel from pydantic.v1 import BaseModel as V1BaseModel class V1Model(V1BaseModel): a: dict[Optional[str], int] class V2Model(V2BaseModel): a: dict[Optional[str], int] v1_model = V1Model(a={None: 123}) v2_model = V2Model(a={None: 123}) # V1 print(v1_model.json()) #> {"a": {"null": 123}} # V2 print(v2_model.model_dump_json()) #> {"a": {"null": 123}} ``` -------------------------------- ### Manually Rebuild TypeAdapter Schema with Deferred Build (Python) Source: https://docs.pydantic.dev/2.12/concepts/type_adapter Demonstrates how to initialize a TypeAdapter with deferred schema building and then manually trigger the rebuild process. This is useful for handling forward references or optimizing schema construction. ```python from pydantic import ConfigDict, TypeAdapter ta = TypeAdapter('MyInt', config=ConfigDict(defer_build=True)) # some time later, the forward reference is defined MyInt = int ta.rebuild() assert ta.validate_python(1) == 1 ``` -------------------------------- ### Create Subclass of Parametrized RootModel in Python Source: https://docs.pydantic.dev/2.12/concepts/models Illustrates subclassing a Pydantic RootModel that is already parametrized, adding custom methods like `describe` to the model. ```python from pydantic import RootModel class Pets(RootModel[list[str]]): def describe(self) -> str: return f'Pets: {", ".join(self.root)}' my_pets = Pets.model_validate(['dog', 'cat']) print(my_pets.describe()) #> Pets: dog, cat ``` -------------------------------- ### Install Pydantic GCP Secret Manager Integration Source: https://docs.pydantic.dev/2.12/concepts/pydantic_settings Install the necessary package to enable Pydantic settings to use Google Cloud Secret Manager. This command installs the pydantic-settings library with the gcp-secret-manager extra dependency. ```bash pip install "pydantic-settings[gcp-secret-manager]" ``` -------------------------------- ### Define and Load Settings with BaseSettings (Python) Source: https://docs.pydantic.dev/2.12/concepts/pydantic_settings Demonstrates how to define a settings class inheriting from BaseSettings. It shows how to use Pydantic Fields with aliases and validation aliases, and how to configure an environment variable prefix using SettingsConfigDict. The example also illustrates loading nested models and custom types like RedisDsn and ImportString. ```python from collections.abc import Callable from typing import Any from pydantic import ( AliasChoices, AmqpDsn, BaseModel, Field, ImportString, PostgresDsn, RedisDsn, ) from pydantic_settings import BaseSettings, SettingsConfigDict class SubModel(BaseModel): foo: str = 'bar' apple: int = 1 class Settings(BaseSettings): auth_key: str = Field(validation_alias='my_auth_key') api_key: str = Field(alias='my_api_key') redis_dsn: RedisDsn = Field( 'redis://user:pass@localhost:6379/1', validation_alias=AliasChoices('service_redis_dsn', 'redis_url'), ) pg_dsn: PostgresDsn = 'postgres://user:pass@localhost:5432/foobar' amqp_dsn: AmqpDsn = 'amqp://user:pass@localhost:5672/' special_function: ImportString[Callable[[Any], Any]] = 'math.cos' # to override domains: # export my_prefix_domains='["foo.com", "bar.com"]' domains: set[str] = set() # to override more_settings: # export my_prefix_more_settings='{"foo": "x", "apple": 1}' more_settings: SubModel = SubModel() model_config = SettingsConfigDict(env_prefix='my_prefix_') print(Settings().model_dump()) ``` -------------------------------- ### EncodedBytes Usage Example Source: https://docs.pydantic.dev/2.12/api/types An example demonstrating how to use EncodedBytes with a custom encoder and Pydantic models. ```APIDOC ### EncodedBytes Dataclass #### Description A bytes type that is encoded and decoded using the specified encoder. `EncodedBytes` needs an encoder that implements `EncoderProtocol` to operate. #### Example Usage ```python from typing import Annotated from pydantic import BaseModel, EncodedBytes, EncoderProtocol, ValidationError class MyEncoder(EncoderProtocol): @classmethod def decode(cls, data: bytes) -> bytes: if data == b'**undecodable**': raise ValueError('Cannot decode data') return data[13:] @classmethod def encode(cls, value: bytes) -> bytes: return b'**encoded**: ' + value @classmethod def get_json_format(cls) -> str: return 'my-encoder' MyEncodedBytes = Annotated[bytes, EncodedBytes(encoder=MyEncoder)] class Model(BaseModel): my_encoded_bytes: MyEncodedBytes # Initialize the model with encoded data m = Model(my_encoded_bytes=b'**encoded**: some bytes') # Access decoded value print(m.my_encoded_bytes) # > b'some bytes' # Serialize into the encoded form print(m.model_dump()) # > {'my_encoded_bytes': b'**encoded**: some bytes'} ``` #### Parameters - **my_encoded_bytes** (MyEncodedBytes) - Required - The encoded bytes field. #### Response #### Success Response (200) - **my_encoded_bytes** (bytes) - The decoded bytes value. #### Response Example ```json { "my_encoded_bytes": "**encoded**: some bytes" } ``` ``` -------------------------------- ### Pydantic model_serializer Example - Temperature Conversion Source: https://docs.pydantic.dev/2.12/api/functional_serializers An example demonstrating the use of the @model_serializer decorator to customize model serialization. This example converts a temperature value from Fahrenheit to Celsius during serialization if the unit is 'F'. It uses the default 'plain' mode. ```python from typing import Literal from pydantic import BaseModel, model_serializer class TemperatureModel(BaseModel): unit: Literal['C', 'F'] value: int @model_serializer() def serialize_model(self): if self.unit == 'F': return {'unit': 'C', 'value': int((self.value - 32) / 1.8)} return {'unit': self.unit, 'value': self.value} temperature = TemperatureModel(unit='F', value=212) print(temperature.model_dump()) # Expected output: {'unit': 'C', 'value': 100} ``` -------------------------------- ### Configure MkDocs mkdocstrings for Pydantic Documentation Source: https://docs.pydantic.dev/2.12/integrations/documentation This snippet demonstrates how to configure the mkdocstrings plugin within MkDocs to import Pydantic's object inventory. This enables mkdocstrings to correctly parse and display Pydantic API documentation. ```yaml plugins: - mkdocstrings: handlers: python: import: - https://docs.pydantic.dev/latest/objects.inv ``` -------------------------------- ### Load Parsed Arguments into Settings Source (Python) Source: https://docs.pydantic.dev/2.12/concepts/pydantic_settings Demonstrates loading pre-parsed command-line arguments into a Pydantic settings source for an application. It shows how to initialize the application with settings and print the resulting model dump. ```python parsed_args = parser.parse_args(['--food', 'kiwi', '--name', 'ralph']) s = CliApp.run(Settings, cli_args=parsed_args, cli_settings_source=cli_settings) print(s.model_dump()) ``` -------------------------------- ### Perform Custom Initialization with model_post_init (Python) Source: https://docs.pydantic.dev/2.12/api/base_model The `model_post_init` method is designed to be overridden for executing custom initialization logic after a Pydantic model has been constructed. This is particularly useful for performing validations or setting up derived attributes that depend on the complete model state. It accepts a `context` argument for passing additional information during initialization. ```python def model_post_init(self, context: Any, /) -> None: """Override this method to perform additional initialization after `__init__` and `model_construct`. This is useful if you want to do some validation that requires the entire model to be initialized. """ ``` -------------------------------- ### Get Pydantic Version String Source: https://docs.pydantic.dev/2.12/api/version Accesses the `__version__` attribute of the pydantic module to get the Pydantic version string. This is a module-level attribute. ```python __version__ = VERSION ``` -------------------------------- ### Initialize PyprojectTomlConfigSettingsSource in Pydantic Source: https://docs.pydantic.dev/2.12/api/pydantic_settings Initializes a Pydantic settings source that loads configuration from a `pyproject.toml` file. It identifies the TOML file, determines the relevant table header (e.g., `[tool.pydantic-settings]`), and reads the configuration data. ```python def __init__( self, settings_cls: type[BaseSettings], toml_file: Path | None = None, ) -> None: self.toml_file_path = self._pick_pyproject_toml_file( toml_file, settings_cls.model_config.get('pyproject_toml_depth', 0) ) self.toml_table_header: tuple[str, ...] = settings_cls.model_config.get( 'pyproject_toml_table_header', ('tool', 'pydantic-settings') ) self.toml_data = self._read_files(self.toml_file_path) for key in self.toml_table_header: self.toml_data = self.toml_data.get(key, {}) super(TomlConfigSettingsSource, self).__init__(settings_cls, self.toml_data) ``` -------------------------------- ### Define and Use Subcommands and Positional Arguments with Pydantic Settings Source: https://docs.pydantic.dev/2.12/concepts/pydantic_settings Demonstrates defining Pydantic models for subcommands (`Init`, `Clone`) and a main settings model (`Git`) that uses `CliSubCommand` and `CliPositionalArg`. It shows how to parse arguments, retrieve subcommands, and handle errors when no subcommand is provided. ```python import sys from pydantic import BaseModel from pydantic_settings import ( BaseSettings, CliPositionalArg, CliSubCommand, SettingsError, get_subcommand, ) class Init(BaseModel): directory: CliPositionalArg[str] class Clone(BaseModel): repository: CliPositionalArg[str] directory: CliPositionalArg[str] class Git(BaseSettings, cli_parse_args=True, cli_exit_on_error=False): clone: CliSubCommand[Clone] init: CliSubCommand[Init] # Run without subcommands sys.argv = ['example.py'] cmd = Git() assert cmd.model_dump() == {'clone': None, 'init': None} try: # Will raise an error since no subcommand was provided get_subcommand(cmd).model_dump() except SettingsError as err: assert str(err) == 'Error: CLI subcommand is required {clone, init}' # Will not raise an error since subcommand is not required assert get_subcommand(cmd, is_required=False) is None # Run the clone subcommand sys.argv = ['example.py', 'clone', 'repo', 'dest'] cmd = Git() assert cmd.model_dump() == { 'clone': {'repository': 'repo', 'directory': 'dest'}, 'init': None, } # Returns the subcommand model instance (in this case, 'clone') assert get_subcommand(cmd).model_dump() == { 'directory': 'dest', 'repository': 'repo', } ``` -------------------------------- ### Install Flake8 Pydantic Plugin using Pip Source: https://docs.pydantic.dev/2.12/integrations/linting This command installs the flake8-pydantic plugin, which provides linting capabilities for Pydantic models within a Python project. Ensure pip is available in your environment. ```bash pip install flake8-pydantic ``` -------------------------------- ### Pydantic condecimal Example with Greater Than Constraint Source: https://docs.pydantic.dev/2.12/api/types An example showcasing the `condecimal` function to create a Pydantic model with a `Decimal` field constrained to be greater than a specific value. It includes successful instantiation and error handling for invalid input. ```python from decimal import Decimal from pydantic import BaseModel, ValidationError, condecimal class ConstrainedExample(BaseModel): constrained_decimal: condecimal(gt=Decimal('1.0')) m = ConstrainedExample(constrained_decimal=Decimal('1.1')) print(repr(m)) #> ConstrainedExample(constrained_decimal=Decimal('1.1')) try: ConstrainedExample(constrained_decimal=Decimal('0.9')) except ValidationError as e: print(e.errors()) ''' [ { 'type': 'greater_than', 'loc': ('constrained_decimal',), 'msg': 'Input should be greater than 1.0', 'input': Decimal('0.9'), 'ctx': {'gt': Decimal('1.0')}, 'url': 'https://errors.pydantic.dev/2/v/greater_than', } ] ''' ``` -------------------------------- ### Pydantic Settings Initialization with CLI and Environment Options (Python) Source: https://docs.pydantic.dev/2.12/api/pydantic_settings Initializes Pydantic settings by processing values, including environment variables and command-line arguments. It supports numerous configuration options for customizing parsing behavior, such as case sensitivity, nested delimiters, and handling of unknown arguments. Dependencies include Pydantic's core functionality and potentially custom types like `PathType` and `CliSettingsSource`. ```python def __init__( __pydantic_self__, _case_sensitive: bool | None = None, _nested_model_default_partial_update: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = ENV_FILE_SENTINEL, _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _cli_flag_prefix_char: str | None = None, _cli_implicit_flags: bool | None = None, _cli_ignore_unknown_args: bool | None = None, _cli_kebab_case: bool | None = None, _secrets_dir: PathType | None = None, **values: Any, ) -> None: # Uses something other than `self` the first arg to allow "self" as a settable attribute super().__init__( **__pydantic_self__._settings_build_values( values, _case_sensitive=_case_sensitive, _nested_model_default_partial_update=_nested_model_default_partial_update, _env_prefix=_env_prefix, _env_file=_env_file, _env_file_encoding=_env_file_encoding, _env_ignore_empty=_env_ignore_empty, _env_nested_delimiter=_env_nested_delimiter, _env_parse_none_str=_env_parse_none_str, _env_parse_enums=_env_parse_enums, _cli_prog_name=_cli_prog_name, _cli_parse_args=_cli_parse_args, _cli_settings_source=_cli_settings_source, _cli_parse_none_str=_cli_parse_none_str, _cli_hide_none_type=_cli_hide_none_type, _cli_avoid_json=_cli_avoid_json, _cli_enforce_required=_cli_enforce_required, _cli_use_class_docs_for_groups=_cli_use_class_docs_for_groups, _cli_exit_on_error=_cli_exit_on_error, _cli_prefix=_cli_prefix, _cli_flag_prefix_char=_cli_flag_prefix_char, _cli_implicit_flags=_cli_implicit_flags, _cli_ignore_unknown_args=_cli_ignore_unknown_args, _cli_kebab_case=_cli_kebab_case, _secrets_dir=_secrets_dir, ) ) ``` -------------------------------- ### Pydantic model_validator Usage Example Source: https://docs.pydantic.dev/2.12/api/functional_validators Demonstrates how to use the Pydantic `model_validator` decorator with `mode='after'` to validate a model. This example shows creating a `Square` model and validating that width and height match, raising a `ValidationError` if they don't. ```python from typing_extensions import Self from pydantic import BaseModel, ValidationError, model_validator class Square(BaseModel): width: float height: float @model_validator(mode='after') def verify_square(self) -> Self: if self.width != self.height: raise ValueError('width and height do not match') return self s = Square(width=1, height=1) print(repr(s)) #> Square(width=1.0, height=1.0) try: Square(width=1, height=2) except ValidationError as e: print(e) ''' 1 validation error for Square Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict] ''' ``` -------------------------------- ### Pydantic Model Naming Collision Example Source: https://docs.pydantic.dev/2.12/concepts/models Highlights a potential pitfall in Pydantic model definition where a field name might collide with a Python built-in or type annotation, leading to unexpected validation errors. This example shows how naming a field 'int' can cause issues. ```python from typing import Optional from pydantic import BaseModel class Boo(BaseModel): int: Optional[int] = None m = Boo(int=123) # Will fail to validate. ``` -------------------------------- ### Instantiate and Validate a Pydantic Model Source: https://docs.pydantic.dev/2.12/concepts/models Shows how to create an instance of the 'User' Pydantic model. Pydantic automatically handles parsing and validation of the input data during instantiation. If validation fails, a ValidationError is raised. ```python user = User(id='123') ``` -------------------------------- ### Create Generic Pydantic HTTP Response Wrapper (Python 3.9+) Source: https://docs.pydantic.dev/2.12/concepts/models Demonstrates creating a generic Pydantic model 'Response' to wrap data of any type 'DataT'. It shows instantiation with different data types and handling validation errors. Requires 'pydantic' and 'typing'. ```python from typing import Generic, TypeVar from pydantic import BaseModel, ValidationError DataT = TypeVar('DataT') class DataModel(BaseModel): number: int class Response(BaseModel, Generic[DataT]): data: DataT print(Response[int](data=1)) #> data=1 print(Response[str](data='value')) #> data='value' print(Response[str](data='value').model_dump()) #> {'data': 'value'} data = DataModel(number=1) print(Response[DataModel](data=data).model_dump()) #> {'data': {'number': 1}} try: Response[int](data='value') except ValidationError as e: print(e) """ 1 validation error for Response[int] data Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='value', input_type=str] """ ``` -------------------------------- ### Install Pydantic for AWS Lambda using Pip Source: https://docs.pydantic.dev/2.12/integrations/aws_lambda Installs Pydantic for AWS Lambda functions, ensuring compatibility with the Lambda environment by specifying platform, target directory, Python version, and implementation. This command is crucial for packaging dependencies correctly. ```bash pip install \ --platform manylinux2014_x86_64 \ --target= \ --implementation cp \ --python-version 3.10 \ --only-binary=:all: \ --upgrade pydantic ``` -------------------------------- ### model_post_init method Source: https://docs.pydantic.dev/2.12/api/base_model Override this method to perform additional initialization after `__init__` and `model_construct`. This is useful if you want to do some validation that requires the entire model to be initialized. ```APIDOC ## model_post_init method ### Description Override this method to perform additional initialization after `__init__` and `model_construct`. This is useful if you want to do some validation that requires the entire model to be initialized. ### Method Instance method ### Endpoint N/A (Instance method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **context** (Any) - Optional - Contextual information passed during initialization. ### Request Example ```python class MyModel(BaseModel): # ... other fields ... def model_post_init(self, context: Any) -> None: # Perform additional initialization here print(f"Post-initialization with context: {context}") # Example: Validate that field_a is greater than field_b # if self.field_a <= self.field_b: # raise ValueError("field_a must be greater than field_b") ``` ### Response #### Success Response (200) None (This method does not return a value, it performs actions). #### Response Example N/A ``` -------------------------------- ### RabbitMQ Sender: Serialize Data with Pydantic for Queues Source: https://docs.pydantic.dev/2.12/examples/queues This Python script demonstrates how to use Pydantic models to serialize data into JSON and send it to a RabbitMQ queue. It requires the 'pika' and 'pydantic' libraries. This is the sender part of the RabbitMQ example. ```python import pika from pydantic import BaseModel, EmailStr class User(BaseModel): id: int name: str email: EmailStr connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() QUEUE_NAME = 'user_queue' channel.queue_declare(queue=QUEUE_NAME) def push_to_queue(user_data: User) -> None: serialized_data = user_data.model_dump_json() channel.basic_publish( exchange='', routing_key=QUEUE_NAME, body=serialized_data, ) print(f'Added to queue: {serialized_data}') user1 = User(id=1, name='John Doe', email='john@example.com') user2 = User(id=2, name='Jane Doe', email='jane@example.com') push_to_queue(user1) #> Added to queue: {"id":1,"name":"John Doe","email":"john@example.com"} push_to_queue(user2) #> Added to queue: {"id":2,"name":"Jane Doe","email":"jane@example.com"} connection.close() ``` -------------------------------- ### Pydantic Data Conversion Example Source: https://docs.pydantic.dev/2.12/concepts/models Demonstrates Pydantic's automatic data type casting for model fields. Input data is converted to match the declared types, which may lead to information loss. This example shows integer and float casting from string and binary data, respectively. ```python from pydantic import BaseModel class Model(BaseModel): a: int b: float c: str print(Model(a=3.000, b='2.72', c=b'binary data').model_dump()) #> {'a': 3, 'b': 2.72, 'c': 'binary data'} ``` -------------------------------- ### Customize Settings Source Priority with CLI Source: https://docs.pydantic.dev/2.12/concepts/pydantic_settings Illustrates how to customize the order of settings sources, ensuring that CLI arguments take precedence over environment variables when `CliSettingsSource` is explicitly included and configured. ```python import os import sys from pydantic_settings import ( BaseSettings, CliSettingsSource, PydanticBaseSettingsSource, ) class Settings(BaseSettings): my_foo: str @classmethod def settings_customise_sources( cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource, ) -> tuple[PydanticBaseSettingsSource, ...]: return env_settings, CliSettingsSource(settings_cls, cli_parse_args=True) os.environ['MY_FOO'] = 'from environment' sys.argv = ['example.py', '--my_foo=from cli'] print(Settings().model_dump()) ``` -------------------------------- ### RabbitMQ Receiver: Deserialize and Validate Data with Pydantic Source: https://docs.pydantic.dev/2.12/examples/queues This Python script acts as a receiver for a RabbitMQ queue. It uses Pydantic to deserialize and validate incoming JSON messages. It requires the 'pika' and 'pydantic' libraries. This is the receiver part of the RabbitMQ example. ```python import pika from pydantic import BaseModel, EmailStr class User(BaseModel): id: int name: str email: EmailStr def main(): connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() QUEUE_NAME = 'user_queue' channel.queue_declare(queue=QUEUE_NAME) def process_message( ch: pika.channel.Channel, method: pika.spec.Basic.Deliver, properties: pika.spec.BasicProperties, body: bytes, ): user = User.model_validate_json(body) print(f'Validated user: {repr(user)}') ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_consume(queue=QUEUE_NAME, on_message_callback=process_message) channel.start_consuming() if __name__ == '__main__': try: main() except KeyboardInterrupt: pass ``` -------------------------------- ### Tagged Union Schema Validation Example (Python) Source: https://docs.pydantic.dev/2.12/api/pydantic_core_schema Demonstrates the creation and validation of a tagged union schema using Pydantic V2's `core_schema`. This example shows how to define schemas for different union members ('apple', 'banana') and use a discriminator ('foo') to validate input data. ```python from pydantic_core import core_schema, SchemaValidator apple_schema = core_schema.typed_dict_schema( { 'foo': core_schema.typed_dict_field(core_schema.literal_schema('apple')), 'bar': core_schema.typed_dict_field(core_schema.int_schema()), } ) banana_schema = core_schema.typed_dict_schema( { 'foo': core_schema.typed_dict_field(core_schema.literal_schema('banana')), 'spam': core_schema.typed_dict_field(core_schema.list_schema(items_schema=core_schema.int_schema())) } ) schema = core_schema.tagged_union_schema( choices={ 'apple': apple_schema, 'banana': banana_schema, }, discriminator='foo' ) v = SchemaValidator(schema) assert v.validate_python({'foo': 'apple', 'bar': '123'}) == {'foo': 'apple', 'bar': 123} assert v.validate_python({'foo': 'banana', 'spam': [1, 2, 3]}) == { 'foo': 'banana', 'spam': [1, 2, 3], } ```