pydantic / pydantic

Data validation using Python type hints
https://docs.pydantic.dev
MIT License
21.1k stars 1.9k forks source link

allow alias generator to access FieldInfo, and particularly its aliases #10348

Open MarcBresson opened 2 months ago

MarcBresson commented 2 months ago

Initial Checks

Description

allow alias generator to access FieldInfo, and particularly its aliases.

It would allow users to generate aliases based on already present aliases

def upper_aliases_generator(field_name: str, field_info: FieldInfo) -> list[str]:
    if isinstance(field_info.alias, AliasChoices):
        aliases = list(field_info.alias)
    elif instance(field_info.alias, str):
        aliases = [field_info.alias]

    generated_aliases = [field_name.upper()]
    for alias in aliases:
        generated_aliases.append(alias.upper())

    return generated_aliases

class A(BaseModel):
    model_config = ConfigDict(alias_generator=upper_aliases_generator)

    SmallTest: str = Field(alias=AliasChoices("small_test", "small_test_"), alias_priority=1)

A(SMALLTEST="hey")
#> A(SmallTest="hey")

A(SMALL_TEST="hey")
#> A(SmallTest="hey")

A(SMALL_TEST_="hey")
#> A(SmallTest="hey")

Affected Components

sydney-runkle commented 2 months ago

Interesting feature request! I'm not opposed. Wdyt @Viicos?

sydney-runkle commented 2 months ago

I can open a PR with support for this in v2.10, potentially.

Viicos commented 2 months ago

The thing is we don't support using AliasChoices/AliasPath for alias.

I don't recall exactly how alias_generator plays with validation_alias/serialization_alias, might be good looking into this.

Perhaps https://github.com/pydantic/pydantic/issues/8379 could be tackled first (I don't know if it relates with this issue or not).

sydney-runkle commented 2 months ago

Yeah, #8379 is definitely higher prio.