Debian Codegraph @

model_utils/choices.py

raw
1 from __future__ import annotations
2
3 import copy
4 from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast, overload
5
6 T = TypeVar("T")
7
8 if TYPE_CHECKING:
9 from collections.abc import Iterable, Iterator, Sequence
10
11 # The type aliases defined here are evaluated when the django-stubs mypy plugin
12 # loads this module, so they must be able to execute under the lowest supported
13 # Python VM:
14 # - typing.List, typing.Tuple become obsolete in Pyton 3.9
15 # - typing.Union becomes obsolete in Pyton 3.10
16 from typing import List, Tuple, Union
17
18 from django_stubs_ext import StrOrPromise
19
20 # The type argument 'T' to 'Choices' is the database representation type.
21 _Double = Tuple[T, StrOrPromise]
22 _Triple = Tuple[T, str, StrOrPromise]
23 _Group = Tuple[StrOrPromise, Sequence["_Choice[T]"]]
24 _Choice = Union[_Double[T], _Triple[T], _Group[T]]
25 # Choices can only be given as a single string if 'T' is 'str'.
26 _GroupStr = Tuple[StrOrPromise, Sequence["_ChoiceStr"]]
27 _ChoiceStr = Union[str, _Double[str], _Triple[str], _GroupStr]
28 # Note that we only accept lists and tuples in groups, not arbitrary sequences.
29 # However, annotating it as such causes many problems.
30
31 _DoubleRead = Union[_Double[T], Tuple[StrOrPromise, Iterable["_DoubleRead[T]"]]]
32 _DoubleCollector = List[Union[_Double[T], Tuple[StrOrPromise, "_DoubleCollector[T]"]]]
33 _TripleCollector = List[Union[_Triple[T], Tuple[StrOrPromise, "_TripleCollector[T]"]]]
34
35
36 class Choices(Generic[T]):
37 """
38 A class to encapsulate handy functionality for lists of choices
39 for a Django model field.
40
41 Each argument to ``Choices`` is a choice, represented as either a
42 string, a two-tuple, or a three-tuple.
43
44 If a single string is provided, that string is used as the
45 database representation of the choice as well as the
46 human-readable presentation.
47
48 If a two-tuple is provided, the first item is used as the database
49 representation and the second the human-readable presentation.
50
51 If a triple is provided, the first item is the database
52 representation, the second a valid Python identifier that can be
53 used as a readable label in code, and the third the human-readable
54 presentation. This is most useful when the database representation
55 must sacrifice readability for some reason: to achieve a specific
56 ordering, to use an integer rather than a character field, etc.
57
58 Regardless of what representation of each choice is originally
59 given, when iterated over or indexed into, a ``Choices`` object
60 behaves as the standard Django choices list of two-tuples.
61
62 If the triple form is used, the Python identifier names can be
63 accessed as attributes on the ``Choices`` object, returning the
64 database representation. (If the single or two-tuple forms are
65 used and the database representation happens to be a valid Python
66 identifier, the database representation itself is available as an
67 attribute on the ``Choices`` object, returning itself.)
68
69 Option groups can also be used with ``Choices``; in that case each
70 argument is a tuple consisting of the option group name and a list
71 of options, where each option in the list is either a string, a
72 two-tuple, or a triple as outlined above.
73
74 """
75
76 @overload
77 def __init__(self: Choices[str], *choices: _ChoiceStr):
78 ...
79
80 @overload
81 def __init__(self, *choices: _Choice[T]):
82 ...
83
84 def __init__(self, *choices: _ChoiceStr | _Choice[T]):
85 # list of choices expanded to triples - can include optgroups
86 self._triples: _TripleCollector[T] = []
87 # list of choices as (db, human-readable) - can include optgroups
88 self._doubles: _DoubleCollector[T] = []
89 # dictionary mapping db representation to human-readable
90 self._display_map: dict[T, StrOrPromise | list[_Triple[T]]] = {}
91 # dictionary mapping Python identifier to db representation
92 self._identifier_map: dict[str, T] = {}
93 # set of db representations
94 self._db_values: set[T] = set()
95
96 self._process(choices)
97
98 def _store(
99 self,
100 triple: tuple[T, str, StrOrPromise],
101 triple_collector: _TripleCollector[T],
102 double_collector: _DoubleCollector[T]
103 ) -> None:
104 self._identifier_map[triple[1]] = triple[0]
105 self._display_map[triple[0]] = triple[2]
106 self._db_values.add(triple[0])
107 triple_collector.append(triple)
108 double_collector.append((triple[0], triple[2]))
109
110 def _process(
111 self,
112 choices: Iterable[_ChoiceStr | _Choice[T]],
113 triple_collector: _TripleCollector[T] | None = None,
114 double_collector: _DoubleCollector[T] | None = None
115 ) -> None:
116 if triple_collector is None:
117 triple_collector = self._triples
118 if double_collector is None:
119 double_collector = self._doubles
120
121 def store(c: tuple[Any, str, StrOrPromise]) -> None:
122 self._store(c, triple_collector, double_collector)
123
124 for choice in choices:
125 # The type inference is not very accurate here:
126 # - we lied in the type aliases, stating groups contain an arbitrary Sequence
127 # rather than only list or tuple
128 # - there is no way to express that _ChoiceStr is only used when T=str
129 # - mypy 1.9.0 doesn't narrow types based on the value of len()
130 if isinstance(choice, (list, tuple)):
131 if len(choice) == 3:
132 store(choice)
133 elif len(choice) == 2:
134 if isinstance(choice[1], (list, tuple)):
135 # option group
136 group_name = choice[0]
137 subchoices = choice[1]
138 tc: _TripleCollector[T] = []
139 triple_collector.append((group_name, tc))
140 dc: _DoubleCollector[T] = []
141 double_collector.append((group_name, dc))
142 self._process(subchoices, tc, dc)
143 else:
144 store((choice[0], cast(str, choice[0]), cast('StrOrPromise', choice[1])))
145 else:
146 raise ValueError(
147 "Choices can't take a list of length %s, only 2 or 3"
148 % len(choice)
149 )
150 else:
151 store((choice, choice, choice))
152
153 def __len__(self) -> int:
154 return len(self._doubles)
155
156 def __iter__(self) -> Iterator[_DoubleRead[T]]:
157 return iter(self._doubles)
158
159 def __reversed__(self) -> Iterator[_DoubleRead[T]]:
160 return reversed(self._doubles)
161
162 def __getattr__(self, attname: str) -> T:
163 try:
164 return self._identifier_map[attname]
165 except KeyError:
166 raise AttributeError(attname)
167
168 def __getitem__(self, key: T) -> StrOrPromise | Sequence[_Triple[T]]:
169 return self._display_map[key]
170
171 @overload
172 def __add__(self: Choices[str], other: Choices[str] | Iterable[_ChoiceStr]) -> Choices[str]:
173 ...
174
175 @overload
176 def __add__(self, other: Choices[T] | Iterable[_Choice[T]]) -> Choices[T]:
177 ...
178
179 def __add__(self, other: Choices[Any] | Iterable[_ChoiceStr | _Choice[Any]]) -> Choices[Any]:
180 other_args: list[Any]
181 if isinstance(other, self.__class__):
182 other_args = other._triples
183 else:
184 other_args = list(other)
185 return Choices(*(self._triples + other_args))
186
187 @overload
188 def __radd__(self: Choices[str], other: Iterable[_ChoiceStr]) -> Choices[str]:
189 ...
190
191 @overload
192 def __radd__(self, other: Iterable[_Choice[T]]) -> Choices[T]:
193 ...
194
195 def __radd__(self, other: Iterable[_ChoiceStr] | Iterable[_Choice[T]]) -> Choices[Any]:
196 # radd is never called for matching types, so we don't check here
197 other_args = list(other)
198 # The exact type of 'other' depends on our type argument 'T', which
199 # is expressed in the overloading, but lost within this method body.
200 return Choices(*(other_args + self._triples)) # type: ignore[arg-type]
201
202 def __eq__(self, other: object) -> bool:
203 if isinstance(other, self.__class__):
204 return self._triples == other._triples
205 return False
206
207 def __repr__(self) -> str:
208 return '{}({})'.format(
209 self.__class__.__name__,
210 ', '.join("%s" % repr(i) for i in self._triples)
211 )
212
213 def __contains__(self, item: T) -> bool:
214 return item in self._db_values
215
216 def __deepcopy__(self, memo: dict[int, Any] | None) -> Choices[T]:
217 args: list[Any] = copy.deepcopy(self._triples, memo)
218 return self.__class__(*args)
219
220 def subset(self, *new_identifiers: str) -> Choices[T]:
221 identifiers = set(self._identifier_map.keys())
222
223 if not identifiers.issuperset(new_identifiers):
224 raise ValueError(
225 'The following identifiers are not present: %s' %
226 identifiers.symmetric_difference(new_identifiers),
227 )
228
229 args: list[Any] = [
230 choice for choice in self._triples
231 if choice[1] in new_identifiers
232 ]
233 return self.__class__(*args)