Adapt external naming conventions
A Python API exchanges PascalCase keys while model attributes use snake_case.
Pydantic · Pipe
alias_generator is a ConfigDict option that derives field aliases from their names. A callable applies to both validation and serialization; AliasGenerator supports different rules for each.
Set alias_generator in ConfigDict to a callable that receives each field name and returns its alias. The same callable applies during validation and serialization; use AliasGenerator when those two directions need different rules.
model_config = ConfigDict(alias_generator=callable_or_alias_generator)| Name | Type | Description |
|---|---|---|
alias_generator | Callable[[str], str] | AliasGenerator | None | A callable mapping a field name to an alias, an AliasGenerator instance for separate validation and serialization rules, or None. |
AliasGenerator when validation and serialization require separate alias rules.AliasGenerator, or None.AliasGenerator if input and output naming must differ.from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_pascal
class Voice(BaseModel):
model_config = ConfigDict(alias_generator=to_pascal)
name: str
language_code: str
voice = Voice(Name="Filiz", LanguageCode="tr-TR")
print(voice.model_dump(by_alias=True))
The generator converts field names to PascalCase for input aliases and serialized output.
A Python API exchanges PascalCase keys while model attributes use snake_case.
A model must accept one naming convention but serialize another.
Multiple fields need consistent generated aliases without declaring each alias manually.
alias_generator do?alias_generator is a configuration option whose value can be a callable, an AliasGenerator, or None. A callable maps each field name to an alias and is used for both validation and serialization.
Follow-up: How would you use separate rules for input and output? Use an AliasGenerator instance rather than one callable, because it supports distinct validation and serialization generators.
alias_generator configured and typed?Configure it through model_config = ConfigDict(alias_generator=...). The callable receives a field name and returns the alias used by the model.
Follow-up: What should the callable return? It should return a string alias for the supplied field name; the documented type is Callable[[str], str].
Pydantic includes to_pascal, to_camel, and to_snake as built-in alias generators. For example, to_pascal maps language_code to LanguageCode, which can be used for model input and alias-based serialization.
Follow-up: How do you emit aliases when dumping a model? Call model_dump(by_alias=True) so serialization uses the generated aliases.
ConfigDictAliasGeneratorto_pascalto_camelto_snakeBaseModel.model_dump