Coverage for src/wonka/managers.py: 99%
78 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-30 22:54 +0000
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-30 22:54 +0000
1"""Manager classes for iterable constructors.
3Contents:
4 Assembler (`MutableSequence`, `base.Manager`): iterable that stores a list
5 of constructors that build an item like an assembly line.
7"""
9from __future__ import annotations
11import copy
12import dataclasses
13from collections.abc import Iterable, Iterator, MutableSequence, Sequence
14from typing import Any, Self, overload
16from . import base, shared, utilities
19@dataclasses.dataclass
20class Assembler(MutableSequence[base.Constructor], base.Manager):
21 """Assembly line constructor.
23 Assembler stores a sequence of wonka constructors that are called by the
24 `manage` (or `create`) method in order to construct an item.
26 Args:
27 contents: stored constructors. Defaults to an empty list.
29 """
31 contents: MutableSequence[base.Constructor] = dataclasses.field(
32 default_factory = list)
34 """ Public Methods """
36 def add(self, item: base.Constructor | Sequence[base.Constructor]) -> None:
37 """Adds `item` to the `contents` attribute.
39 Args:
40 item: item(s) to add to `contents` attribute.
42 Raises:
43 TypeError: if all of the values of `item` are not wonka-compatible
44 constructors.
46 """
47 if shared.is_constructor(item):
48 self.contents.append(item)
49 elif (
50 isinstance(item, Sequence)
51 and all(shared.is_constructor(v) for v in item)):
52 self.contents.extend(item)
53 else:
54 message = 'All values in item must be wonka-compatible constructors'
55 raise TypeError(message)
57 def delete(self, item: int | slice) -> None:
58 """Deletes item(s) at the index or slice in `contents`.
60 Args:
61 item: index or slice in `contents` to delete.
63 Raises:
64 IndexError: if `item` is an index that is not in `contents`.
66 """
67 del self.contents[item]
69 def insert(self, index: int, value: base.Constructor) -> None:
70 """Inserts `value` at `index` in `contents`.
72 `MutableSequence` uses this method for `append`, `extend`, and `+=`, so
73 those methods are validated too.
75 Args:
76 index: index to insert `value` at.
77 value: constructor to be inserted.
79 """
80 _validate_constructors([value])
81 self.contents.insert(index, value)
83 def manage(self, item: Any, **kwargs: base.Kwargs) -> Any:
84 """Manages construction and/or modification based on `item`.
86 Args:
87 item: item to be passed to constructors in `contents`.
88 **kwargs: keyword arguments passed to each constructor.
90 Returns:
91 Constructed item.
93 """
94 for constructor in self.contents:
95 item = constructor.create(item, **kwargs)
96 return item
98 def prepend(
99 self,
100 item: base.Constructor | Sequence[base.Constructor]) -> None:
101 """Prepends `item` to `contents`.
103 If `item` is a sequence of constructors (and not a constructor itself,
104 such as an `Assembler`), `prepend` adds its contents to the stored list
105 in the order they appear in `item`.
107 Args:
108 item: item(s) to prepend to `contents`.
110 Raises:
111 TypeError: if all of the values of `item` are not wonka-compatible
112 constructors.
114 """
115 if shared.is_constructor(item):
116 self.insert(0, item)
117 elif isinstance(item, Sequence) and not isinstance(item, str):
118 _validate_constructors(item)
119 self.contents[0:0] = list(item)
120 else:
121 message = 'All values in item must be wonka-compatible constructors'
122 raise TypeError(message)
124 def subset(
125 self,
126 include: Any | Sequence[Any] | None = None,
127 exclude: Any | Sequence[Any] | None = None) -> Self:
128 """Returns a new instance with a subset of `contents`.
130 This method applies `include` before `exclude` if both are passed. If
131 `include` is `None`, all existing items will be added to the new subset
132 class instance before `exclude` is applied.
134 Args:
135 include: item(s) to include in the new instance. Defaults to `None`.
136 exclude: item(s) to exclude in the new instance. Defaults to `None`.
138 Raises:
139 ValueError: if `include` and `exclude` are both `None`.
141 Returns:
142 Assembler with only items from `include` and no items in `exclude`.
144 """
145 if include is None and exclude is None:
146 message = 'include or exclude must not be None'
147 raise ValueError(message)
148 contents = list(self.contents)
149 if include is not None:
150 included = list(utilities._iterify(include))
151 contents = [i for i in contents if i in included]
152 if exclude is not None:
153 excluded = list(utilities._iterify(exclude))
154 contents = [i for i in contents if i not in excluded]
155 new_assembler = copy.copy(self)
156 new_assembler.contents = copy.deepcopy(contents)
157 return new_assembler
159 """ Dunder Methods """
161 @overload
162 def __getitem__(self, index: int) -> base.Constructor: ...
164 @overload
165 def __getitem__(self, index: slice) -> MutableSequence[base.Constructor]:
166 ...
168 def __getitem__(
169 self,
170 index: int | slice) -> (
171 base.Constructor | MutableSequence[base.Constructor]):
172 """Returns value(s) for `index` in `contents`.
174 Args:
175 index: index or slice to search for in `contents`.
177 Returns:
178 Item stored in `contents` at `index` or the items in the slice.
180 """
181 return self.contents[index]
183 @overload
184 def __setitem__(self, index: int, value: base.Constructor) -> None: ...
186 @overload
187 def __setitem__( 187 ↛ exitline 187 didn't return from function '__setitem__' because
188 self,
189 index: slice,
190 value: Iterable[base.Constructor]) -> None: ...
192 def __setitem__(
193 self,
194 index: int | slice,
195 value: base.Constructor | Iterable[base.Constructor]) -> None:
196 """Sets `index` in `contents` to `value`.
198 Args:
199 index: index or slice to set `value` to in `contents`.
200 value: constructor (or, for a slice, constructors) to be set at
201 `index` in `contents`.
203 """
204 if isinstance(index, slice):
205 values = list(value) # type: ignore[arg-type]
206 _validate_constructors(values)
207 self.contents[index] = values
208 else:
209 _validate_constructors([value])
210 self.contents[index] = value # type: ignore[assignment]
212 def __add__(
213 self,
214 other: base.Constructor | Sequence[base.Constructor]) -> Self:
215 """Returns a deep copy with `other` combined using the `add` method.
217 Args:
218 other: item to add to the copy's `contents` using the `add` method.
220 Returns:
221 A new instance. The original instance is not modified.
223 """
224 new_assembler = copy.deepcopy(self)
225 new_assembler.add(item = other)
226 return new_assembler
228 def __iadd__( # type: ignore[override]
229 self,
230 other: base.Constructor | Sequence[base.Constructor]) -> Self:
231 """Combines argument with `contents` using the `add` method.
233 Args:
234 other: item to add to `contents` using the `add` method.
236 Returns:
237 The instance, modified in place.
239 """
240 self.add(item = other)
241 return self
243 def __delitem__(self, index: int | slice) -> None:
244 """Deletes item(s) at `index` in `contents`.
246 Args:
247 index: index or slice of item(s) to delete in `contents`.
249 """
250 self.delete(item = index)
252 def __iter__(self) -> Iterator[base.Constructor]:
253 """Returns iterator of `contents`.
255 Returns:
256 Iterator of `contents`.
258 """
259 return iter(self.contents)
261 def __len__(self) -> int:
262 """Returns length of `contents`.
264 Returns:
265 Length of `contents`.
267 """
268 return len(self.contents)
271""" Private Functions """
274def _validate_constructors(items: Iterable[Any]) -> None:
275 """Raises an error if any of `items` is not a wonka-compatible constructor.
277 Args:
278 items: items to validate.
280 Raises:
281 TypeError: if any of `items` is not a wonka-compatible constructor.
283 """
284 if not all(shared.is_constructor(i) for i in items):
285 message = 'All values in item must be wonka-compatible constructors'
286 raise TypeError(message)