1"""Support for alias configurations."""
2
3from __future__ import annotations
4
5import dataclasses
6from typing import Any, Callable, Literal
7
8from pydantic_core import PydanticUndefined
9
10from ._internal import _internal_dataclass
11
12__all__ = ('AliasGenerator', 'AliasPath', 'AliasChoices')
13
14
15@dataclasses.dataclass(**_internal_dataclass.slots_true)
16class AliasPath:
17 """!!! abstract "Usage Documentation"
18 [`AliasPath` and `AliasChoices`](../concepts/alias.md#aliaspath-and-aliaschoices)
19
20 A data class used by `validation_alias` as a convenience to create aliases.
21
22 Attributes:
23 path: A list of string or integer aliases.
24 """
25
26 path: list[int | str]
27
28 def __init__(self, first_arg: str, *args: str | int) -> None:
29 self.path = [first_arg] + list(args)
30
31 def convert_to_aliases(self) -> list[str | int]:
32 """Converts arguments to a list of string or integer aliases.
33
34 Returns:
35 The list of aliases.
36 """
37 return self.path
38
39 def search_dict_for_path(self, d: dict) -> Any:
40 """Searches a dictionary for the path specified by the alias.
41
42 Returns:
43 The value at the specified path, or `PydanticUndefined` if the path is not found.
44 """
45 v = d
46 for k in self.path:
47 if isinstance(v, str):
48 # disallow indexing into a str, like for AliasPath('x', 0) and x='abc'
49 return PydanticUndefined
50 try:
51 v = v[k]
52 except (KeyError, IndexError, TypeError):
53 return PydanticUndefined
54 return v
55
56
57@dataclasses.dataclass(**_internal_dataclass.slots_true)
58class AliasChoices:
59 """!!! abstract "Usage Documentation"
60 [`AliasPath` and `AliasChoices`](../concepts/alias.md#aliaspath-and-aliaschoices)
61
62 A data class used by `validation_alias` as a convenience to create aliases.
63
64 Attributes:
65 choices: A list containing a string or `AliasPath`.
66 """
67
68 choices: list[str | AliasPath]
69
70 def __init__(self, first_choice: str | AliasPath, *choices: str | AliasPath) -> None:
71 self.choices = [first_choice] + list(choices)
72
73 def convert_to_aliases(self) -> list[list[str | int]]:
74 """Converts arguments to a list of lists containing string or integer aliases.
75
76 Returns:
77 The list of aliases.
78 """
79 aliases: list[list[str | int]] = []
80 for c in self.choices:
81 if isinstance(c, AliasPath):
82 aliases.append(c.convert_to_aliases())
83 else:
84 aliases.append([c])
85 return aliases
86
87
88@dataclasses.dataclass(**_internal_dataclass.slots_true)
89class AliasGenerator:
90 """!!! abstract "Usage Documentation"
91 [Using an `AliasGenerator`](../concepts/alias.md#using-an-aliasgenerator)
92
93 A data class used by `alias_generator` as a convenience to create various aliases.
94
95 Attributes:
96 alias: A callable that takes a field name and returns an alias for it.
97 validation_alias: A callable that takes a field name and returns a validation alias for it.
98 serialization_alias: A callable that takes a field name and returns a serialization alias for it.
99 """
100
101 alias: Callable[[str], str] | None = None
102 validation_alias: Callable[[str], str | AliasPath | AliasChoices] | None = None
103 serialization_alias: Callable[[str], str] | None = None
104
105 def _generate_alias(
106 self,
107 alias_kind: Literal['alias', 'validation_alias', 'serialization_alias'],
108 allowed_types: tuple[type[str] | type[AliasPath] | type[AliasChoices], ...],
109 field_name: str,
110 ) -> str | AliasPath | AliasChoices | None:
111 """Generate an alias of the specified kind. Returns None if the alias generator is None.
112
113 Raises:
114 TypeError: If the alias generator produces an invalid type.
115 """
116 alias = None
117 if alias_generator := getattr(self, alias_kind):
118 alias = alias_generator(field_name)
119 if alias and not isinstance(alias, allowed_types):
120 raise TypeError(
121 f'Invalid `{alias_kind}` type. `{alias_kind}` generator must produce one of `{allowed_types}`'
122 )
123 return alias
124
125 def generate_aliases(self, field_name: str) -> tuple[str | None, str | AliasPath | AliasChoices | None, str | None]:
126 """Generate `alias`, `validation_alias`, and `serialization_alias` for a field.
127
128 Returns:
129 A tuple of three aliases - validation, alias, and serialization.
130 """
131 alias = self._generate_alias('alias', (str,), field_name)
132 validation_alias = self._generate_alias('validation_alias', (str, AliasChoices, AliasPath), field_name)
133 serialization_alias = self._generate_alias('serialization_alias', (str,), field_name)
134
135 return alias, validation_alias, serialization_alias # type: ignore