Skip to content

pydantic aliases: snake_case or kebab-case? #334

@disinvite

Description

@disinvite

In our pydantic models for importing and exporting the reccmp-*.yml files, we use AliasChoice to allow multiple options for variable name. We mainly use this to allow both snake_case and kebab-case keys in the YML.

pydantic describes this feature as:

AliasChoices is used to specify a list of choices of aliases. Choices that appear first in the list will have higher priority during validation.

Observe that in this example, the key test-field is used regardless of order.

import ruamel.yaml
from pydantic import AliasChoices, BaseModel, Field

_yaml = ruamel.yaml.YAML()

text = """\
test-field: 123
test_field: 555
"""

reversed = """\
test_field: 555
test-field: 123
"""

class Sample(BaseModel):
    test_field: int = Field(
        validation_alias=AliasChoices("test-field", "test_field"),
    )

x = Sample.model_validate(_yaml.load(text))
y = Sample.model_validate(_yaml.load(reversed))

assert x.test_field == 123
assert y.test_field == 123

Do we want this behavior? It is at least consistent and predictable, but I would've expected a duplicate alias to raise an exception.

YAML forbids duplicate keys. JSON cautions against using them because the behavior is undefined and implementation-specific.

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs investigationthe truth is out therequestionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions