new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Pydantic · API reference · all subjects

aliases

17 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

pydantic.aliases module

The pydantic.aliases module provides functionality for handling field aliases in Pydantic models.

Field alias types and specification

An alias is an alternative name for a field, used when serializing and deserializing data. Aliases can be specified in four ways: (1) `alias` on Field — must be a `str`; (2) `validation_alias` on Field — can be a `str`, `AliasPath`, or `AliasChoices`; (3) `serialization_alias` on Field — must be a `str`; (4) `alias_generator` on ConfigDict — can be a callable or `AliasGenerator` instance.

AliasPath usage

AliasPath is used to specify a path to a field using aliases. It accepts positional arguments that can be strings (for dictionary keys) or integers (for list indices). For example, `AliasPath('names', 0)` accesses index 0 of the 'names' key, and `AliasPath('contact', 'address')` accesses nested dictionary keys.

AliasPath example with nested data

from pydantic import BaseModel, Field, AliasPath class User(BaseModel): first_name: str = Field(validation_alias=AliasPath('names', 0)) last_name: str = Field(validation_alias=AliasPath('names', 1)) address: str = Field(validation_alias=AliasPath('contact', 'address')) user = User.model_validate({ 'names': ['John', 'Doe'], 'contact': {'address': '221B Baker Street'} }) print(user) #> first_name='John' last_name='Doe' address='221B Baker Street'

AliasChoices usage and priority

AliasChoices is used to specify multiple alias choices. Choices that appear first in the list have higher priority during validation. If multiple choices are provided in the input data, the one with highest priority (appearing earlier in the AliasChoices list) is used.

AliasChoices with AliasPath

AliasChoices can be combined with AliasPath. This allows specifying multiple validation options where each option can be either a simple string alias or a path-based alias.

AliasChoices and AliasPath combined example

from pydantic import BaseModel, Field, AliasPath, AliasChoices class User(BaseModel): first_name: str = Field(validation_alias=AliasChoices('first_name', AliasPath('names', 0))) last_name: str = Field(validation_alias=AliasChoices('last_name', AliasPath('names', 1))) user = User.model_validate({'first_name': 'John', 'last_name': 'Doe'}) print(user) #> first_name='John' last_name='Doe' user = User.model_validate({'names': ['John', 'Doe']}) print(user) #> first_name='John' last_name='Doe' user = User.model_validate({'names': ['John'], 'last_name': 'Doe'}) print(user) #> first_name='John' last_name='Doe'

Built-in alias generators

Pydantic provides three built-in alias generators: `to_pascal`, `to_camel`, and `to_snake`. These can be used directly with the `alias_generator` parameter in ConfigDict.

alias_generator with callable example

from pydantic import BaseModel, ConfigDict class Tree(BaseModel): model_config = ConfigDict( alias_generator=lambda field_name: field_name.upper() ) age: int height: float kind: str t = Tree.model_validate({'AGE': 12, 'HEIGHT': 1.2, 'KIND': 'oak'}) print(t.model_dump(by_alias=True)) #> {'AGE': 12, 'HEIGHT': 1.2, 'KIND': 'oak'}

AliasGenerator class usage

AliasGenerator is a class that allows specifying multiple alias generators for a model. It can be used to specify different alias generators for validation and serialization separately.

AliasGenerator with validation and serialization aliases example

from pydantic import AliasGenerator, BaseModel, ConfigDict class Tree(BaseModel): model_config = ConfigDict( alias_generator=AliasGenerator( validation_alias=lambda field_name: field_name.upper(), serialization_alias=lambda field_name: field_name.title(), ) ) age: int height: float kind: str t = Tree.model_validate({'AGE': 12, 'HEIGHT': 1.2, 'KIND': 'oak'}) print(t.model_dump(by_alias=True)) #> {'Age': 12, 'Height': 1.2, 'Kind': 'oak'}

Alias precedence over alias_generator

If an `alias` is specified on a Field, it takes precedence over the generated alias by default.

alias_priority field parameter values

The `alias_priority` parameter on a field controls whether an alias is overridden by alias_generator. Allowed values are: `alias_priority=2` — alias will not be overridden by alias_generator; `alias_priority=1` — alias will be overridden by alias_generator; `alias_priority` not set — if alias is set, it will not be overridden; if alias is not set, it will be overridden by alias_generator.

alias_priority with alias_generator example

from pydantic import BaseModel, ConfigDict, Field def to_camel(string: str) -> str: return ''.join(word.capitalize() for word in string.split('_')) class Voice(BaseModel): model_config = ConfigDict(alias_generator=to_camel) name: str language_code: str = Field(alias='lang') voice = Voice(Name='Filiz', lang='tr-TR') print(voice.language_code) #> tr-TR print(voice.model_dump(by_alias=True)) #> {'Name': 'Filiz', 'lang': 'tr-TR'}

validate_call Field with aliases

Aliases can be used with the validate_call decorator as normal, specified through the alias parameter of the Field() function when used with Annotated type hints.

Field() alias parameters

Field() accepts three alias-related parameters: 'alias' (used for both validation and serialization), 'validation_alias' (used only for validation), and 'serialization_alias' (used only for serialization). If multiple alias parameters are provided, validation_alias has priority over alias for validation, and serialization_alias has priority over alias for serialization. The by_alias parameter in model_dump() defaults to False.

Field() validation_alias with serialization_alias workaround

When using validation_alias for validation only while maintaining type checker support, specify both alias and serialization_alias with identical values: Field(alias='myValidationAlias', serialization_alias='my_field'). The serialization_alias overrides the alias during serialization, achieving validation-only alias behavior while satisfying type checkers.

Give your agent this brain