### Running Documentation Tests and Updating Examples Source: https://pydantic.dev/docs/validation/latest/get-started/contributing This command runs the documentation tests and updates code examples within the documentation. Use this to ensure your code examples are correct and formatted properly. ```bash # Run tests and update code examples pytest tests/test_docs.py --update-examples ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://pydantic.dev/docs/validation/latest/get-started/contributing Steps to clone your Pydantic fork, install development tools like uv and pre-commit, and install Pydantic with its dependencies using make. ```bash # 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-settings Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Install the pydantic-settings library using pip. ```terminal pip install pydantic-settings ``` -------------------------------- ### Install Pydantic with uv Source: https://pydantic.dev/docs/validation/latest/get-started/install Use this command to install the core Pydantic package using uv. ```bash uv add pydantic ``` -------------------------------- ### Install datamodel-code-generator Source: https://pydantic.dev/docs/validation/latest/integrations/dev-tools/datamodel_code_generator Install the package using pip. ```bash pip install datamodel-code-generator ``` -------------------------------- ### Install Pydantic from repository with uv Source: https://pydantic.dev/docs/validation/latest/get-started/install Install Pydantic directly from its GitHub repository using uv. You can also include optional extras. ```bash uv add 'git+https://github.com/pydantic/pydantic@main'# or with `email` and `timezone` extras:uv add 'git+https://github.com/pydantic/pydantic@main#egg=pydantic[email,timezone]' ``` -------------------------------- ### Install Pydantic with optional email dependency using uv Source: https://pydantic.dev/docs/validation/latest/get-started/install Install Pydantic with the 'email' extra dependency using uv. ```bash # with the `email` extra:uv add 'pydantic[email]'# or with `email` and `timezone` extras:uv add 'pydantic[email,timezone]' ``` -------------------------------- ### Install Bump Pydantic Tool Source: https://pydantic.dev/docs/validation/latest/get-started/migration Command to install the beta migration tool for updating codebases to Pydantic V2. ```bash pip install bump-pydantic ``` -------------------------------- ### Install Pydantic V2 Source: https://pydantic.dev/docs/validation/latest/get-started/migration Command to install the current production release of Pydantic. ```bash pip install -U pydantic ``` -------------------------------- ### Install Pydantic V1 Source: https://pydantic.dev/docs/validation/latest/get-started/migration Command to install the latest version of Pydantic V1. ```bash pip install "pydantic==1.*" ``` -------------------------------- ### Usage of nullable_schema Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example showing how to create a schema that matches a nullable value. ```python from pydantic_core import SchemaValidator, core_schemaschema = core_schema.nullable_schema(core_schema.str_schema())v = SchemaValidator(schema)assert v.validate_python(None) is None ``` -------------------------------- ### Usage of with_default_schema Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example showing how to add a default value to a schema. ```python from pydantic_core import SchemaValidator, core_schemaschema = core_schema.with_default_schema(core_schema.str_schema(), default='hello')wrapper_schema = core_schema.typed_dict_schema( {'a': core_schema.typed_dict_field(schema)})v = SchemaValidator(wrapper_schema)assert v.validate_python({}) == v.validate_python({'a': 'hello'}) ``` -------------------------------- ### Usage of union_schema Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example showing how to create a schema that matches a union value. ```python from pydantic_core import SchemaValidator, core_schemaschema = core_schema.union_schema([core_schema.str_schema(), core_schema.int_schema()])v = SchemaValidator(schema)assert v.validate_python('hello') == 'hello'assert v.validate_python(1) == 1 ``` -------------------------------- ### Example JSON file content Source: https://pydantic.dev/docs/validation/latest/examples/files A sample JSON file structure representing a single person. ```json { "name": "John Doe", "age": 30, "email": "john@example.com"} ``` -------------------------------- ### Install Pydantic from repository with pip Source: https://pydantic.dev/docs/validation/latest/get-started/install Install Pydantic directly from its GitHub repository using pip. You can also include optional extras. ```bash pip install 'git+https://github.com/pydantic/pydantic@main'# or with `email` and `timezone` extras:pip install 'git+https://github.com/pydantic/pydantic@main#egg=pydantic[email,timezone]' ``` -------------------------------- ### Install Pydantic with pip Source: https://pydantic.dev/docs/validation/latest/get-started/install Use this command to install the core Pydantic package using pip. ```bash pip install pydantic ``` -------------------------------- ### Install Pydantic with optional email dependency using pip Source: https://pydantic.dev/docs/validation/latest/get-started/install Install Pydantic with the 'email' extra dependency using pip. ```bash # with the `email` extra:pip install 'pydantic[email]'# or with `email` and `timezone` extras:pip install 'pydantic[email,timezone]' ``` -------------------------------- ### Install Pydantic for AWS Lambda Source: https://pydantic.dev/docs/validation/latest/integrations/aws_lambda Use this command to install Pydantic and its dependencies for AWS Lambda, ensuring compatibility with the Lambda environment. Adjust platform and Python version as needed. ```bash pip install --platform manylinux2014_x86_64 --target= --implementation cp --python-version 3.10 --only-binary=:all: --upgrade pydantic ``` -------------------------------- ### Install Pydantic Settings with GCP Secret Manager Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Install the necessary package to enable Google Cloud Secret Manager integration with Pydantic settings. ```bash pip install "pydantic-settings[gcp-secret-manager]" ``` -------------------------------- ### Example Pydantic Settings Structure Source: https://pydantic.dev/docs/validation/latest/api/pydantic_settings Demonstrates a nested structure for Pydantic BaseSettings models, including lists and dictionaries. ```python class SubSubModel(BaseSettings): dvals: Dict class SubModel(BaseSettings): vals: list[str] sub_sub_model: SubSubModel class Cfg(BaseSettings): sub_model: SubModel ``` -------------------------------- ### Implement a tagged union schema Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example demonstrating how to define schemas for different cases and use a discriminator to select the appropriate schema during validation. ```python from pydantic_core import SchemaValidator, core_schemaapple_schema = core_schema.typed_dict_schema( { 'foo': core_schema.typed_dict_field(core_schema.str_schema()), '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.str_schema()), '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],} ``` -------------------------------- ### JSON Schema input file Source: https://pydantic.dev/docs/validation/latest/integrations/dev-tools/datamodel_code_generator Example JSON Schema file used as input for model generation. ```json { "$id": "person.json", "$schema": "http://json-schema.org/draft-07/schema#", "title": "Person", "type": "object", "properties": { "first_name": { "type": "string", "description": "The person's first name." }, "last_name": { "type": "string", "description": "The person's last name." }, "age": { "description": "Age in years.", "type": "integer", "minimum": 0 }, "pets": { "type": "array", "items": [ { "$ref": "#/definitions/Pet" } ] }, "comment": { "type": "null" } }, "required": [ "first_name", "last_name" ], "definitions": { "Pet": { "properties": { "name": { "type": "string" }, "age": { "type": "integer" } } } }} ``` -------------------------------- ### Nested Secrets Directory Structure Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Example of a nested secrets directory structure with default and override configurations. ```text πŸ“‚ secretsβ”œβ”€β”€ πŸ“‚ defaultβ”‚ β”œβ”€β”€ πŸ“‚ appβ”‚ β”‚ └── πŸ“„ keyβ”‚ └── πŸ“‚ dbβ”‚ └── πŸ“„ passwd└── πŸ“‚ override β”œβ”€β”€ πŸ“‚ app β”‚ └── πŸ“„ key └── πŸ“‚ db └── πŸ“„ passwd ``` -------------------------------- ### Change Settings Source Priority Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Override `settings_customise_sources` to change the order of built-in sources. This example prioritizes environment variables over init kwargs. ```python from pydantic import PostgresDsn from pydantic_settings import BaseSettings, PydanticBaseSettingsSource class Settings(BaseSettings): database_dsn: PostgresDsn @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, init_settings, file_secret_settings print(Settings(database_dsn='postgres://postgres@localhost:5432/kwargs_db')) ``` -------------------------------- ### Demonstrating Runtime NameError with Forward References Source: https://pydantic.dev/docs/validation/latest/internals/resolving_annotations This example shows how referencing a class before it is defined results in a NameError at runtime. ```python class Node: """Binary tree node.""" # NameError: name 'Node' is not defined: def __init__(self, l: Node, r: Node) -> None: self.left = l self.right = r ``` -------------------------------- ### Define and Use Subcommands and Positional Arguments Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Demonstrates defining `Init` and `Clone` models with positional arguments and a `Git` settings model with subcommands. Shows how to parse arguments, handle missing subcommands, and retrieve subcommand instances. ```python import sysfrom pydantic import BaseModelfrom 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 subcommands 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', } ``` -------------------------------- ### Build Documentation Source: https://pydantic.dev/docs/validation/latest/get-started/contributing Command to build the project's documentation locally. This is important if you have made changes to documentation files, function signatures, or docstrings. ```bash # 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 ``` -------------------------------- ### Load Settings from pyproject.toml Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Demonstrates loading settings from the default `[tool.pydantic-settings]` table, a custom table, and the root of the pyproject.toml file. ```python from pydantic_settings import ( BaseSettings, PydanticBaseSettingsSource, PyprojectTomlConfigSettingsSource, SettingsConfigDict, ) class Settings(BaseSettings): """Example loading values from the table used by default.""" field: 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 (PyprojectTomlConfigSettingsSource(settings_cls),) class SomeTableSettings(Settings): """Example loading values from a user defined table.""" model_config = SettingsConfigDict( pyproject_toml_table_header=('tool', 'some-table') ) class RootSettings(Settings): """Example loading values from the root of a pyproject.toml file.""" model_config = SettingsConfigDict(extra='ignore', pyproject_toml_table_header=()) ``` -------------------------------- ### Install Pydantic with conda Source: https://pydantic.dev/docs/validation/latest/get-started/install Use this command to install Pydantic from the conda-forge channel. ```bash conda install pydantic -c conda-forge ``` -------------------------------- ### Recommended Annotated StringConstraints usage Source: https://pydantic.dev/docs/validation/latest/api/pydantic/types This example demonstrates the recommended way to apply string constraints using `Annotated` and `StringConstraints`. This approach is preferred for better static analysis compatibility. ```python from typing import Annotated from pydantic import BaseModel, StringConstraints class Foo(BaseModel): bar: Annotated[ str, StringConstraints( strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$' ), ] ``` -------------------------------- ### Install flake8-pydantic Plugin Source: https://pydantic.dev/docs/validation/latest/integrations/dev-tools/linting Install the flake8-pydantic plugin using pip. This enables Pydantic-specific linting rules. ```bash pip install flake8-pydantic ``` -------------------------------- ### Load Settings from Multiple TOML Files Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Shows how to load settings from a list of TOML files, where settings are merged shallowly in the order provided. Later files override earlier ones. ```python from pydantic import BaseModel from pydantic_settings import ( BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict, TomlConfigSettingsSource, ) class Nested(BaseModel): foo: int bar: int = 0 class Settings(BaseSettings): hello: str nested: Nested model_config = SettingsConfigDict( toml_file=['config.default.toml', 'config.custom.toml'] ) @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 (TomlConfigSettingsSource(settings_cls),) ``` ```toml # config.default.toml hello = "World" [nested] foo = 1 bar = 2 ``` ```toml # config.custom.toml [nested] foo = 3 ``` ```toml hello = "world" [nested] foo = 3 ``` -------------------------------- ### UserIn and UserOut Pattern in Python Source: https://pydantic.dev/docs/validation/latest/concepts/experimental This example demonstrates an alternative pattern for handling input and output models using plain Python. It's useful when you need simpler type checking and easier error reporting to users. ```python from __future__ import annotationsfrom pydantic import BaseModelclass UserIn(BaseModel): favorite_number: int | strclass UserOut(BaseModel): favorite_number: intdef my_api(user: UserIn) -> UserOut: favorite_number = user.favorite_number if isinstance(favorite_number, str): favorite_number = int(user.favorite_number.strip()) return UserOut(favorite_number=favorite_number) assert my_api(UserIn(favorite_number=' 1 ')).favorite_number == 1 ``` -------------------------------- ### Run Tests and Linting Source: https://pydantic.dev/docs/validation/latest/get-started/contributing Run the main make command to execute all tests and linting checks for Pydantic. Use `make help` for more specific commands like `test` or `lint`. ```bash # Run tests and linting make # There are a few sub-commands in Makefile like `test`, `testcov` and `lint` # which you might want to use, but generally just `make` should be all you need. # You can run `make help` to see more options. ``` -------------------------------- ### Define and Load Settings with Pydantic Settings Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Example demonstrating how to define a settings model inheriting from BaseSettings and how it loads values from environment variables, including aliasing and nested models. Ensure environment variables are set for fields like 'my_auth_key', 'my_api_key', 'service_redis_dsn' or 'redis_url', and 'my_prefix_domains', 'my_prefix_more_settings' to see overrides in action. ```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') # (2) redis_dsn: RedisDsn = Field( 'redis://user:pass@localhost:6379/1', validation_alias=AliasChoices('service_redis_dsn', 'redis_url'), # (3) ) 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' # (4) # 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_') # (5) print(Settings().model_dump()) ``` -------------------------------- ### Documenting a Function Source: https://pydantic.dev/docs/validation/latest/get-started/contributing Functions should be documented using Google-style docstrings, including 'Args' for parameters and 'Returns' for the return value. This example demonstrates documenting a function that takes an integer and returns a string. ```python def bar(self, baz: int) -> str: """A function docstring. Args: baz: A description of `baz`. Returns: A description of the return value. """ return 'bar' ``` -------------------------------- ### Get Pydantic Version Info (v2+) Source: https://pydantic.dev/docs/validation/latest/get-started/contributing Use this command to get version information for Pydantic v2 and later. Include this output when reporting issues. ```python python -c "import pydantic.version; print(pydantic.version.version_info())" ``` -------------------------------- ### Get Pydantic Version Info (pre-v2) Source: https://pydantic.dev/docs/validation/latest/get-started/contributing Use this command to get version information for Pydantic versions prior to v2.0. Include this output when reporting issues. ```python python -c "import pydantic.utils; print(pydantic.utils.version_info())" ``` -------------------------------- ### TypeAdapter Constructor Source: https://pydantic.dev/docs/validation/latest/api/pydantic/type_adapter Explains the parameters used when initializing a TypeAdapter instance. ```APIDOC ## TypeAdapter Constructor ### Description Initializes a `TypeAdapter` instance to perform validation and serialization based on a Python type. ### Parameters #### Constructor Parameters - **type** (Any) - Required - The type associated with the `TypeAdapter`. - **config** (ConfigDict | None) - Optional - Default: None - Configuration for the `TypeAdapter`, should be a dictionary conforming to `ConfigDict`. Cannot be provided if the type has its own non-overridable config (e.g., `BaseModel`, `TypedDict`, `dataclass`). - **_parent_depth** (int) - Optional - Default: 2 - Depth at which to search for the parent frame for resolving forward annotations. - **module** (str | None) - Optional - Default: None - The module that passes to plugin if provided. ``` -------------------------------- ### Example: With Info Before Validator Function Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Shows how to use `with_info_before_validator_function` where the validator receives `ValidationInfo`. This example decodes bytes to a string, using info to assert field context. ```python from pydantic_core import SchemaValidator, core_schema def fn(v: bytes, info: core_schema.ValidationInfo) -> str: assert info.data is not None assert info.field_name is not None return v.decode() + 'world' func_schema = core_schema.with_info_before_validator_function( function=fn, schema=core_schema.str_schema()) schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)}) v = SchemaValidator(schema) assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'} ``` -------------------------------- ### Run Formatting and Linting Source: https://pydantic.dev/docs/validation/latest/get-started/contributing Execute the make format command to automatically fix code formatting and linting issues using ruff. ```bash # Run automated code formatting and linting make format # Pydantic uses ruff, an awesome Python linter written in rust # https://github.com/astral-sh/ruff ``` -------------------------------- ### Validate with model_fields_schema Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example usage of model_fields_schema to validate input data. ```python from pydantic_core import SchemaValidator, core_schemawrapper_schema = core_schema.model_fields_schema( {'a': core_schema.model_field(core_schema.str_schema())})v = SchemaValidator(wrapper_schema)print(v.validate_python({'a': 'hello'}))#> ({'a': 'hello'}, None, {'a'}) ``` -------------------------------- ### Creating and Serializing a Cyclic Graph Source: https://pydantic.dev/docs/validation/latest/concepts/forward_annotations This example demonstrates creating a cyclic graph of `Node` objects and then serializing it using `TypeAdapter` to show how the custom serializer handles the circular references. ```python # Create a cyclic graph: nodes = [Node(id=1), Node(id=2), Node(id=3)] nodes[0].children.append(nodes[1]) nodes[1].children.append(nodes[2]) nodes[2].children.append(nodes[0]) print(nodes[0]) #> Node(id=1, children=[Node(id=2, children=[Node(id=3, children=[...])])]) # Serialize the cyclic graph: print(TypeAdapter(Node).dump_python(nodes[0])) """ { 'id': 1, 'children': [{'id': 2, 'children': [{'id': 3, 'children': [{'id': 1}]}]}], } """ ``` -------------------------------- ### Add Custom JSON Settings Source Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Create a custom settings source class to load variables from a JSON file. This example defines `JsonConfigSettingsSource` and integrates it into the settings customization. ```python import json from pathlib import Path from typing import Any from pydantic.fields import FieldInfo from pydantic_settings import ( BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict, ) class JsonConfigSettingsSource(PydanticBaseSettingsSource): """ A simple settings source class that loads variables from a JSON file at the project's root. Here we happen to choose to use the `env_file_encoding` from Config when reading `config.json` """ def get_field_value( self, field: FieldInfo, field_name: str ) -> tuple[Any, str, bool]: encoding = self.config.get('env_file_encoding') file_content_json = json.loads( Path('tests/example_test_config.json').read_text(encoding) ) field_value = file_content_json.get(field_name) return field_value, field_name, False def prepare_field_value( self, field_name: str, field: FieldInfo, value: Any, value_is_complex: bool ) -> Any: return value def __call__(self) -> dict[str, Any]: d: dict[str, Any] = {} for field_name, field in self.settings_cls.model_fields.items(): field_value, field_key, value_is_complex = self.get_field_value( field, field_name ) field_value = self.prepare_field_value( field_name, field, field_value, value_is_complex ) if field_value is not None: d[field_key] = field_value return d class Settings(BaseSettings): model_config = SettingsConfigDict(env_file_encoding='utf-8') foobar: 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 ( init_settings, JsonConfigSettingsSource(settings_cls), env_settings, file_secret_settings, ) print(Settings()) ``` -------------------------------- ### Usage of no_info_plain_validator_function Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example demonstrating a simple plain validator function. ```python from pydantic_core import SchemaValidator, core_schemadef fn(v: str) -> str: assert 'hello' in v return v + 'world'schema = core_schema.no_info_plain_validator_function(function=fn)v = SchemaValidator(schema)assert v.validate_python('hello ') == 'hello world' ``` -------------------------------- ### Usage of with_info_wrap_validator_function Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example demonstrating the middleware-like behavior of a wrap validator. ```python from pydantic_core import SchemaValidator, core_schemadef fn( v: str, validator: core_schema.ValidatorFunctionWrapHandler, info: core_schema.ValidationInfo,) -> str: return validator(input_value=v) + 'world'schema = core_schema.with_info_wrap_validator_function( function=fn, schema=core_schema.str_schema())v = SchemaValidator(schema)assert v.validate_python('hello ') == 'hello world' ``` -------------------------------- ### Get Argument Name Source: https://pydantic.dev/docs/validation/latest/api/pydantic/json_schema Retrieves the name of an argument from its schema representation. ```APIDOC ## get_argument_name ### Description Retrieves the name of an argument. ### Method N/A (Function Definition) ### Endpoint N/A (Function Definition) ### Parameters #### Arguments - **argument** (core_schema.ArgumentsParameter | core_schema.ArgumentsV3Parameter) - Required - The core schema representing the argument. ### Returns `str` β€” The name of the argument. ``` -------------------------------- ### GET /get_timezones Source: https://pydantic.dev/docs/validation/latest/api/pydantic-extra-types/pydantic_extra_types_timezone_name Retrieves the set of all available timezones from the configured provider. ```APIDOC ## GET /get_timezones ### Description Determine the timezone provider and return available timezones. ### Returns - **set[str]** - A set containing all valid timezone strings. ``` -------------------------------- ### Load .env via instantiation argument Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Override or specify the .env file to load during the instantiation of a BaseSettings class using the `_env_file` keyword argument. ```python from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8') settings = Settings(_env_file='prod.env', _env_file_encoding='utf-8') ``` -------------------------------- ### Validate with model_schema Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example usage of model_schema to define and validate a model class. ```python from pydantic_core import CoreConfig, SchemaValidator, core_schemaclass MyModel: __slots__ = ( '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__', )schema = core_schema.model_schema( cls=MyModel, config=CoreConfig(str_max_length=5), schema=core_schema.model_fields_schema( fields={'a': core_schema.model_field(core_schema.str_schema())}, ),)v = SchemaValidator(schema)assert v.isinstance_python({'a': 'hello'}) is Trueassert v.isinstance_python({'a': 'too long'}) is False ``` -------------------------------- ### format_help Source: https://pydantic.dev/docs/validation/latest/api/pydantic_settings Generates a help message for a Pydantic model. ```APIDOC ## format_help ### Description Return a string containing a help message for a Pydantic model. ### Parameters - **model** (PydanticModel | type[T]) - Required - The model or model class. - **cli_settings_source** (CliSettingsSource[Any] | None) - Optional - Override the default CLI settings source. Defaults to None. - **strip_ansi_color** (bool) - Optional - Strips ANSI color codes from the help message when set to True. Defaults to False. ### Returns - **str** - The help message string for the model. ``` -------------------------------- ### Handle Unions and Aliases with Subcommands and Positional Arguments Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Illustrates using `Union` types for subcommands and applying aliases to fields. Shows how different alias configurations affect CLI help text and subcommand names for union and non-union types. ```python import sysfrom typing import Unionfrom pydantic import BaseModel, Fieldfrom pydantic_settings import ( BaseSettings, CliPositionalArg, CliSubCommand, get_subcommand, ) class Alpha(BaseModel): """Apha Help""" cmd_alpha: CliPositionalArg[str] = Field(alias='alpha-cmd') class Beta(BaseModel): """Beta Help""" opt_beta: str = Field(alias='opt-beta') class Gamma(BaseModel): """Gamma Help""" opt_gamma: str = Field(alias='opt-gamma') class Root(BaseSettings, cli_parse_args=True, cli_exit_on_error=False): alpha_or_beta: CliSubCommand[Union[Alpha, Beta]] = Field(alias='alpha-or-beta-cmd') gamma: CliSubCommand[Gamma] = Field(alias='gamma-cmd') sys.argv = ['example.py', 'Alpha', 'hello'] assert get_subcommand(Root()).model_dump() == {'cmd_alpha': 'hello'} sys.argv = ['example.py', 'Beta', '--opt-beta=hey'] assert get_subcommand(Root()).model_dump() == {'opt_beta': 'hey'} sys.argv = ['example.py', 'gamma-cmd', '--opt-gamma=hi'] assert get_subcommand(Root()).model_dump() == {'opt_gamma': 'hi'} ``` -------------------------------- ### Load Settings from TOML File Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Demonstrates how to configure Pydantic Settings to load from a single TOML configuration file. Ensure the 'config.toml' file exists in the working directory. ```python from pydantic import BaseModel from pydantic_settings import ( BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict, TomlConfigSettingsSource, ) class Nested(BaseModel): nested_field: str class Settings(BaseSettings): foobar: str nested: Nested model_config = SettingsConfigDict(toml_file='config.toml') @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 (TomlConfigSettingsSource(settings_cls),) ``` ```toml foobar = "Hello" [nested] nested_field = "world!" ``` -------------------------------- ### Import ModelField from V1 Source: https://pydantic.dev/docs/validation/latest/get-started/migration Example of importing ModelField using the pydantic.v1 namespace. ```python from pydantic.v1.fields import ModelField ``` -------------------------------- ### Validate a decimal value Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example of using decimal_schema to validate a decimal input. ```python from decimal import Decimalfrom pydantic_core import SchemaValidator, core_schemaschema = core_schema.decimal_schema(le=0.8, ge=0.2)v = SchemaValidator(schema)assert v.validate_python('0.5') == Decimal('0.5') ``` -------------------------------- ### Validate a float value Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example of using float_schema to validate a numeric input. ```python from pydantic_core import SchemaValidator, core_schemaschema = core_schema.float_schema(le=0.8, ge=0.2)v = SchemaValidator(schema)assert v.validate_python('0.5') == 0.5 ``` -------------------------------- ### Define model_post_init for post-initialization logic Source: https://pydantic.dev/docs/validation/latest/concepts/models Use model_post_init to perform actions after model initialization instead of overriding __init__. ```python import loggingfrom typing import Anyfrom pydantic import BaseModelclass MyModel(BaseModel): id: int def model_post_init(self, context: Any) -> None: logging.info("Model initialized with id %d", self.id) ``` -------------------------------- ### Get JSON format for encoder Source: https://pydantic.dev/docs/validation/latest/api/pydantic/types Retrieves the JSON format string for the encoder. ```python @classmethod def get_json_format(cls) -> str ``` -------------------------------- ### Print and Format Help Text in Pydantic Settings CLI Source: https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings Use `CliApp.print_help` to display help directly or `CliApp.format_help` to get a formatted string. This can be done on an instance or the class itself. ```python from pydantic_settings import BaseSettings, CliApp class Settings(BaseSettings, cli_prog_name='example'): def cli_cmd(self) -> None: # Will print help for the current command or subcommand instance. CliApp.print_help(self) # Will return formatted help for the current command or subcommand instance. CliApp.format_help(self) CliApp.run(Settings, cli_args=[]) """usage: example [-h] options: -h, --help show this help message and exit """ # You can also print or format help on the class itself. print(CliApp.format_help(Settings)) ``` -------------------------------- ### Usage of with_info_plain_validator_function Source: https://pydantic.dev/docs/validation/latest/api/pydantic-core/pydantic_core_schema Example demonstrating a plain validator function that accepts validation info. ```python from pydantic_core import SchemaValidator, core_schemadef fn(v: str, info: core_schema.ValidationInfo) -> str: assert 'hello' in v return v + 'world'schema = core_schema.with_info_plain_validator_function(function=fn)v = SchemaValidator(schema)assert v.validate_python('hello ') == 'hello world' ``` -------------------------------- ### JSON file with a list of objects Source: https://pydantic.dev/docs/validation/latest/examples/files A sample JSON file containing an array of person objects. ```json [ { "name": "John Doe", "age": 30, "email": "john@example.com" }, { "name": "Jane Doe", "age": 25, "email": "jane@example.com" }] ``` -------------------------------- ### Basic Dynamic Model Creation Source: https://pydantic.dev/docs/validation/latest/concepts/models Demonstrates the basic usage of `create_model` to define a model with string and integer fields, including a default value. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new user resources. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of users to return. #### Request Body - **username** (string) - Required - The username for the new user. - **email** (string) - Required - The email address for the new user. - **age** (integer) - Optional - The age of the user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "age": 30 } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. - **age** (integer) - The age of the created user. #### Response Example ```json { "id": 1, "username": "johndoe", "email": "john.doe@example.com", "age": 30 } ``` ``` -------------------------------- ### Import V1 BaseModel Source: https://pydantic.dev/docs/validation/latest/get-started/migration Example of importing the V1 BaseModel class while using Pydantic V2. ```python from pydantic.v1 import BaseModel ``` -------------------------------- ### Demonstrate make_fields_optional Factory Function Source: https://pydantic.dev/docs/validation/latest/examples/dynamic_models Demonstrates the usage of the `make_fields_optional` factory function to create a new model with optional fields and shows an instance with a default `None` value. ```python from pydantic import BaseModel, Field class Model(BaseModel): a: Annotated[int, Field(gt=1)] ModelOptional = make_fields_optional(Model) m = ModelOptional() print(m.a)#> None ``` -------------------------------- ### Pydantic Literal Example Source: https://pydantic.dev/docs/validation/latest/api/pydantic/standard_library_types Demonstrates the use of `Literal` for strict value validation in Pydantic models. ```APIDOC ## Pydantic Literal Validation ### Description This example shows how to use `typing.Literal` to restrict a field to a specific set of values or numbers. It also demonstrates how Pydantic raises `ValidationError` when an invalid value is provided. ### Method N/A (Illustrative Example) ### Endpoint N/A ### Request Body Example ```python from typing import Literal from pydantic import BaseModel, ValidationError class Pie(BaseModel): flavor: Literal['apple', 'pumpkin'] quantity: Literal[1, 2] = 1 # Valid examples print(Pie(flavor='apple')) print(Pie(flavor='pumpkin')) # Invalid examples try: Pie(flavor='cherry') except ValidationError as e: print(str(e)) # Output: # 1 validation error for Pie # flavor Input should be 'apple' or 'pumpkin' [type=literal_error, input_value='cherry', input_type=str] try: Pie(flavor='apple', quantity='1') except ValidationError as e: print(str(e)) # Output: # 1 validation error for Pie # quantity Input should be 1 or 2 [type=literal_error, input_value='1', input_type=str] ``` ### Response Example N/A ``` -------------------------------- ### Instantiate a model Source: https://pydantic.dev/docs/validation/latest/concepts/models Create a model instance, which triggers validation and type coercion. ```python user = User(id='123') ``` -------------------------------- ### model_validator usage example Source: https://pydantic.dev/docs/validation/latest/api/pydantic/functional_validators Demonstrates using model_validator with mode='after' to verify consistency between multiple fields. ```python from typing_extensions import Selffrom pydantic import BaseModel, ValidationError, model_validatorclass 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 selfs = 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] ''' ```