python-utils 2.5.6__py3-none-any.whl → 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,637 @@
1
+ """
2
+ This module provides custom container classes with enhanced functionality.
3
+
4
+ Classes::
5
+
6
+ CastedDictBase: Abstract base class for dictionaries that cast keys and
7
+ values.
8
+ CastedDict: Dictionary that casts keys and values to specified types.
9
+ LazyCastedDict: Dictionary that lazily casts values to specified types upon
10
+ access.
11
+ UniqueList: List that only allows unique values, with configurable behavior
12
+ on duplicates.
13
+ SliceableDeque: Deque that supports slicing and enhanced equality checks.
14
+
15
+ Type Aliases::
16
+
17
+ KT: Type variable for dictionary keys.
18
+ VT: Type variable for dictionary values.
19
+ DT: Type alias for a dictionary with keys of type KT and values of type VT.
20
+ KT_cast: Type alias for a callable that casts dictionary keys.
21
+ VT_cast: Type alias for a callable that casts dictionary values.
22
+ HT: Type variable for hashable values in UniqueList.
23
+ T: Type variable for generic types.
24
+ DictUpdateArgs: Union type for arguments that can be used to update a
25
+ dictionary.
26
+ OnDuplicate: Literal type for handling duplicate values in UniqueList.
27
+
28
+ Usage::
29
+
30
+ - CastedDict and LazyCastedDict can be used to create dictionaries with
31
+ automatic type casting.
32
+ - UniqueList ensures all elements are unique and can raise an error on
33
+ duplicates.
34
+ - SliceableDeque extends deque with slicing support and enhanced equality
35
+ checks.
36
+
37
+ Examples:
38
+ >>> d = CastedDict(int, int)
39
+ >>> d[1] = 2
40
+ >>> d['3'] = '4'
41
+ >>> d.update({'5': '6'})
42
+ >>> d.update([('7', '8')])
43
+ >>> d
44
+ {1: 2, 3: 4, 5: 6, 7: 8}
45
+
46
+ >>> l = UniqueList(1, 2, 3)
47
+ >>> l.append(4)
48
+ >>> l.append(4)
49
+ >>> l.insert(0, 4)
50
+ >>> l.insert(0, 5)
51
+ >>> l[1] = 10
52
+ >>> l
53
+ [5, 10, 2, 3, 4]
54
+
55
+ >>> d = SliceableDeque([1, 2, 3, 4, 5])
56
+ >>> d[1:4]
57
+ SliceableDeque([2, 3, 4])
58
+ """
59
+
60
+ # pyright: reportIncompatibleMethodOverride=false
61
+ import abc
62
+ import collections
63
+ import collections.abc
64
+ import typing
65
+
66
+ if typing.TYPE_CHECKING:
67
+ import _typeshed # noqa: F401
68
+
69
+ #: A type alias for a type that can be used as a key in a dictionary.
70
+ KT = typing.TypeVar('KT')
71
+ #: A type alias for a type that can be used as a value in a dictionary.
72
+ VT = typing.TypeVar('VT')
73
+ #: A type alias for a dictionary with keys of type KT and values of type VT.
74
+ DT = dict[KT, VT]
75
+ #: A type alias for the casted type of a dictionary key.
76
+ KT_cast = collections.abc.Callable[..., KT] | None
77
+ #: A type alias for the casted type of a dictionary value.
78
+ VT_cast = collections.abc.Callable[..., VT] | None
79
+ #: A type alias for the hashable values of the `UniqueList`
80
+ HT = typing.TypeVar('HT', bound=collections.abc.Hashable)
81
+ #: A type alias for a regular generic type
82
+ T = typing.TypeVar('T')
83
+
84
+ #: Argument shapes accepted when updating a casted dict: a mapping, an iterable
85
+ #: of key/value pairs, an iterable of mappings, or a keys-and-getitem object.
86
+ # Kept as `typing.Union` (not PEP 604 `|`): one member is a string forward
87
+ # reference, and `|` evaluates its operands eagerly, raising `TypeError` on a
88
+ # `str` operand at runtime. `typing.Union` accepts it as a lazy `ForwardRef`.
89
+ DictUpdateArgs = typing.Union[
90
+ collections.abc.Mapping[KT, VT],
91
+ collections.abc.Iterable[tuple[KT, VT]],
92
+ collections.abc.Iterable[collections.abc.Mapping[KT, VT]],
93
+ '_typeshed.SupportsKeysAndGetItem[KT, VT]',
94
+ ]
95
+
96
+ #: Policy for ``UniqueList`` duplicates: silently ``'ignore'`` or ``'raise'``.
97
+ OnDuplicate = typing.Literal['ignore', 'raise']
98
+
99
+
100
+ class CastedDictBase(dict[KT, VT], abc.ABC):
101
+ """
102
+ Abstract base class for dictionaries that cast keys and values.
103
+
104
+ Attributes:
105
+ _key_cast (KT_cast[KT]): Callable to cast dictionary keys.
106
+ _value_cast (VT_cast[VT]): Callable to cast dictionary values.
107
+
108
+ Methods::
109
+
110
+ __init__(key_cast: KT_cast[KT] = None, value_cast: VT_cast[VT] = None,
111
+ *args: DictUpdateArgs[KT, VT], **kwargs: VT) -> None:
112
+ Initializes the dictionary with optional key and value casting
113
+ callables.
114
+ update(*args: DictUpdateArgs[typing.Any, typing.Any],
115
+ **kwargs: typing.Any) -> None:
116
+ Updates the dictionary with the given arguments.
117
+ __setitem__(key: typing.Any, value: typing.Any) -> None:
118
+ Sets the item in the dictionary, casting the key if a key cast
119
+ callable is provided.
120
+ """
121
+
122
+ _key_cast: KT_cast[KT]
123
+ _value_cast: VT_cast[VT]
124
+
125
+ def __init__(
126
+ self,
127
+ key_cast: KT_cast[KT] = None,
128
+ value_cast: VT_cast[VT] = None,
129
+ *args: DictUpdateArgs[KT, VT],
130
+ **kwargs: VT,
131
+ ) -> None:
132
+ """
133
+ Initializes the CastedDictBase with optional key and value
134
+ casting callables.
135
+
136
+ Args:
137
+ key_cast (KT_cast[KT], optional): Callable to cast
138
+ dictionary keys. Defaults to None.
139
+ value_cast (VT_cast[VT], optional): Callable to cast
140
+ dictionary values. Defaults to None.
141
+ *args (DictUpdateArgs[KT, VT]): Arguments to initialize
142
+ the dictionary.
143
+ **kwargs (VT): Keyword arguments to initialize the
144
+ dictionary.
145
+ """
146
+ self._value_cast = value_cast
147
+ self._key_cast = key_cast
148
+ self.update(*args, **kwargs)
149
+
150
+ def update(
151
+ self,
152
+ *args: DictUpdateArgs[typing.Any, typing.Any],
153
+ **kwargs: typing.Any,
154
+ ) -> None:
155
+ """
156
+ Updates the dictionary with the given arguments.
157
+
158
+ Args:
159
+ *args (DictUpdateArgs[typing.Any, typing.Any]): Arguments to update
160
+ the dictionary.
161
+ **kwargs (typing.Any): Keyword arguments to update the dictionary.
162
+ """
163
+ if args:
164
+ kwargs.update(*args)
165
+
166
+ if kwargs:
167
+ for key, value in kwargs.items():
168
+ self[key] = value
169
+
170
+ def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
171
+ """
172
+ Sets the item in the dictionary, casting the key if a key cast
173
+ callable is provided.
174
+
175
+ Args:
176
+ key (typing.Any): The key to set in the dictionary.
177
+ value (typing.Any): The value to set in the dictionary.
178
+ """
179
+ if self._key_cast is not None:
180
+ key = self._key_cast(key)
181
+
182
+ return super().__setitem__(key, value)
183
+
184
+
185
+ class CastedDict(CastedDictBase[KT, VT]):
186
+ """
187
+ Custom dictionary that casts keys and values to the specified types.
188
+
189
+ Note that you can specify the types for mypy and type hinting with:
190
+ CastedDict[int, int](int, int)
191
+
192
+ >>> d: CastedDict[int, int] = CastedDict(int, int)
193
+ >>> d[1] = 2
194
+ >>> d['3'] = '4'
195
+ >>> d.update({'5': '6'})
196
+ >>> d.update([('7', '8')])
197
+ >>> d
198
+ {1: 2, 3: 4, 5: 6, 7: 8}
199
+ >>> list(d.keys())
200
+ [1, 3, 5, 7]
201
+ >>> list(d)
202
+ [1, 3, 5, 7]
203
+ >>> list(d.values())
204
+ [2, 4, 6, 8]
205
+ >>> list(d.items())
206
+ [(1, 2), (3, 4), (5, 6), (7, 8)]
207
+ >>> d[3]
208
+ 4
209
+
210
+ # Casts are optional and can be disabled by passing None as the cast
211
+ >>> d = CastedDict()
212
+ >>> d[1] = 2
213
+ >>> d['3'] = '4'
214
+ >>> d.update({'5': '6'})
215
+ >>> d.update([('7', '8')])
216
+ >>> d
217
+ {1: 2, '3': '4', '5': '6', '7': '8'}
218
+ """
219
+
220
+ def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
221
+ """Cast ``value`` (if a value cast is set) and store it under ``key``.
222
+
223
+ The key itself is cast by ``CastedDictBase.__setitem__`` when a key
224
+ cast is configured.
225
+ """
226
+ if self._value_cast is not None:
227
+ value = self._value_cast(value)
228
+
229
+ super().__setitem__(key, value)
230
+
231
+
232
+ class LazyCastedDict(CastedDictBase[KT, VT]):
233
+ """
234
+ Custom dictionary that casts keys and lazily casts values to the specified
235
+ types. Note that the values are cast only when they are accessed and
236
+ are not cached between executions.
237
+
238
+ Note that you can specify the types for mypy and type hinting with:
239
+ LazyCastedDict[int, int](int, int)
240
+
241
+ >>> d: LazyCastedDict[int, int] = LazyCastedDict(int, int)
242
+ >>> d[1] = 2
243
+ >>> d['3'] = '4'
244
+ >>> d.update({'5': '6'})
245
+ >>> d.update([('7', '8')])
246
+ >>> d
247
+ {1: 2, 3: '4', 5: '6', 7: '8'}
248
+ >>> list(d.keys())
249
+ [1, 3, 5, 7]
250
+ >>> list(d)
251
+ [1, 3, 5, 7]
252
+ >>> list(d.values())
253
+ [2, 4, 6, 8]
254
+ >>> list(d.items())
255
+ [(1, 2), (3, 4), (5, 6), (7, 8)]
256
+ >>> d[3]
257
+ 4
258
+
259
+ # Casts are optional and can be disabled by passing None as the cast
260
+ >>> d = LazyCastedDict()
261
+ >>> d[1] = 2
262
+ >>> d['3'] = '4'
263
+ >>> d.update({'5': '6'})
264
+ >>> d.update([('7', '8')])
265
+ >>> d
266
+ {1: 2, '3': '4', '5': '6', '7': '8'}
267
+ >>> list(d.keys())
268
+ [1, '3', '5', '7']
269
+ >>> list(d.values())
270
+ [2, '4', '6', '8']
271
+
272
+ >>> list(d.items())
273
+ [(1, 2), ('3', '4'), ('5', '6'), ('7', '8')]
274
+ >>> d['3']
275
+ '4'
276
+ """
277
+
278
+ def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
279
+ """
280
+ Sets the item in the dictionary, casting the key if a key cast
281
+ callable is provided.
282
+
283
+ Args:
284
+ key (typing.Any): The key to set in the dictionary.
285
+ value (typing.Any): The value to set in the dictionary.
286
+ """
287
+ if self._key_cast is not None:
288
+ key = self._key_cast(key)
289
+
290
+ super().__setitem__(key, value)
291
+
292
+ def __getitem__(self, key: typing.Any) -> VT:
293
+ """
294
+ Gets the item from the dictionary, casting the value if a value cast
295
+ callable is provided.
296
+
297
+ Args:
298
+ key (typing.Any): The key to get from the dictionary.
299
+
300
+ Returns:
301
+ VT: The value from the dictionary.
302
+ """
303
+ if self._key_cast is not None:
304
+ key = self._key_cast(key)
305
+
306
+ value = super().__getitem__(key)
307
+
308
+ if self._value_cast is not None:
309
+ value = self._value_cast(value)
310
+
311
+ return value
312
+
313
+ def items( # type: ignore[override]
314
+ self,
315
+ ) -> collections.abc.Generator[tuple[KT, VT], None, None]:
316
+ """
317
+ Returns a generator of the dictionary's items, casting the values if a
318
+ value cast callable is provided.
319
+
320
+ Yields:
321
+ Generator[tuple[KT, VT], None, None]: A generator of
322
+ the dictionary's items.
323
+ """
324
+ if self._value_cast is None:
325
+ yield from super().items()
326
+ else:
327
+ for key, value in super().items():
328
+ yield key, self._value_cast(value)
329
+
330
+ def values(self) -> collections.abc.Generator[VT, None, None]: # type: ignore[override]
331
+ """
332
+ Returns a generator of the dictionary's values, casting the values if a
333
+ value cast callable is provided.
334
+
335
+ Yields:
336
+ Generator[VT, None, None]: A generator of the dictionary's
337
+ values.
338
+ """
339
+ if self._value_cast is None:
340
+ yield from super().values()
341
+ else:
342
+ for value in super().values():
343
+ yield self._value_cast(value)
344
+
345
+
346
+ class UniqueList(list[HT]):
347
+ """
348
+ A list that only allows unique values. Duplicate values are ignored by
349
+ default, but can be configured to raise an exception instead.
350
+
351
+ >>> l = UniqueList(1, 2, 3)
352
+ >>> l.append(4)
353
+ >>> l.append(4)
354
+ >>> l.insert(0, 4)
355
+ >>> l.insert(0, 5)
356
+ >>> l[1] = 10
357
+ >>> l
358
+ [5, 10, 2, 3, 4]
359
+
360
+ >>> l = UniqueList(1, 2, 3, on_duplicate='raise')
361
+ >>> l.append(4)
362
+ >>> l.append(4)
363
+ Traceback (most recent call last):
364
+ ...
365
+ ValueError: Duplicate value: 4
366
+ >>> l.insert(0, 4)
367
+ Traceback (most recent call last):
368
+ ...
369
+ ValueError: Duplicate value: 4
370
+ >>> 4 in l
371
+ True
372
+ >>> l[0]
373
+ 1
374
+ >>> l[1] = 4
375
+ Traceback (most recent call last):
376
+ ...
377
+ ValueError: Duplicate value: 4
378
+ """
379
+
380
+ _set: set[HT]
381
+
382
+ def __init__(
383
+ self,
384
+ *args: HT,
385
+ on_duplicate: OnDuplicate = 'ignore',
386
+ ):
387
+ """
388
+ Initializes the UniqueList with optional duplicate handling behavior.
389
+
390
+ Args:
391
+ *args (HT): Initial values for the list.
392
+ on_duplicate (OnDuplicate, optional): Behavior on duplicates.
393
+ Defaults to 'ignore'.
394
+ """
395
+ self.on_duplicate = on_duplicate
396
+ self._set = set()
397
+ super().__init__()
398
+ for arg in args:
399
+ self.append(arg)
400
+
401
+ def insert(self, index: typing.SupportsIndex, value: HT) -> None:
402
+ """
403
+ Inserts a value at the specified index, ensuring uniqueness.
404
+
405
+ Args:
406
+ index (typing.SupportsIndex): The index to insert the value at.
407
+ value (HT): The value to insert.
408
+
409
+ Raises:
410
+ ValueError: If the value is a duplicate and `on_duplicate` is set
411
+ to 'raise'.
412
+ """
413
+ if value in self._set:
414
+ if self.on_duplicate == 'raise':
415
+ raise ValueError(f'Duplicate value: {value}')
416
+ else:
417
+ return
418
+
419
+ self._set.add(value)
420
+ super().insert(index, value)
421
+
422
+ def append(self, value: HT) -> None:
423
+ """
424
+ Appends a value to the list, ensuring uniqueness.
425
+
426
+ Args:
427
+ value (HT): The value to append.
428
+
429
+ Raises:
430
+ ValueError: If the value is a duplicate and `on_duplicate` is set
431
+ to 'raise'.
432
+ """
433
+ if value in self._set:
434
+ if self.on_duplicate == 'raise':
435
+ raise ValueError(f'Duplicate value: {value}')
436
+ else:
437
+ return
438
+
439
+ self._set.add(value)
440
+ super().append(value)
441
+
442
+ def __contains__(self, item: HT) -> bool: # type: ignore[override]
443
+ """
444
+ Checks if the list contains the specified item.
445
+
446
+ Args:
447
+ item (HT): The item to check for.
448
+
449
+ Returns:
450
+ bool: True if the item is in the list, False otherwise.
451
+ """
452
+ return item in self._set
453
+
454
+ @typing.overload
455
+ def __setitem__(self, indices: typing.SupportsIndex, values: HT) -> None:
456
+ """Overload: assign a single value at an integer index."""
457
+
458
+ @typing.overload
459
+ def __setitem__(
460
+ self, indices: slice, values: collections.abc.Iterable[HT]
461
+ ) -> None:
462
+ """Overload: assign an iterable of values to a slice."""
463
+
464
+ def __setitem__(
465
+ self,
466
+ indices: slice | typing.SupportsIndex,
467
+ values: collections.abc.Iterable[HT] | HT,
468
+ ) -> None:
469
+ """
470
+ Sets the item(s) at the specified index/indices, ensuring uniqueness.
471
+
472
+ Args:
473
+ indices (slice | typing.SupportsIndex): The index or
474
+ slice to set the value(s) at.
475
+ values (Iterable[HT] | HT): The value(s) to set.
476
+
477
+ Raises:
478
+ RuntimeError: If `on_duplicate` is 'ignore' and setting slices.
479
+ ValueError: If the value(s) are duplicates and `on_duplicate` is
480
+ set to 'raise'.
481
+ """
482
+ if isinstance(indices, slice):
483
+ values = typing.cast(collections.abc.Iterable[HT], values)
484
+ if self.on_duplicate == 'ignore':
485
+ raise RuntimeError(
486
+ 'ignore mode while setting slices introduces ambiguous '
487
+ 'behaviour and is therefore not supported'
488
+ )
489
+
490
+ duplicates: set[HT] = set(values) & self._set
491
+ if duplicates and values != list(self[indices]):
492
+ raise ValueError(f'Duplicate values: {duplicates}')
493
+
494
+ self._set.update(values)
495
+ else:
496
+ values = typing.cast(HT, values)
497
+ if values in self._set and values != self[indices]:
498
+ if self.on_duplicate == 'raise':
499
+ raise ValueError(f'Duplicate value: {values}')
500
+ else:
501
+ return
502
+
503
+ self._set.add(values)
504
+
505
+ super().__setitem__(
506
+ typing.cast(slice, indices), typing.cast(list[HT], values)
507
+ )
508
+
509
+ def __delitem__(self, index: typing.SupportsIndex | slice) -> None:
510
+ """
511
+ Deletes the item(s) at the specified index/indices.
512
+
513
+ Args:
514
+ index (typing.SupportsIndex | slice): The index or slice
515
+ to delete the item(s) at.
516
+ """
517
+ if isinstance(index, slice):
518
+ for value in self[index]:
519
+ self._set.remove(value)
520
+ else:
521
+ self._set.remove(self[index])
522
+
523
+ super().__delitem__(index)
524
+
525
+
526
+ # Type hinting `collections.deque` does not work consistently between Python
527
+ # runtime, mypy and pyright currently so we have to ignore the errors
528
+ class SliceableDeque(typing.Generic[T], collections.deque[T]):
529
+ """
530
+ A deque that supports slicing and enhanced equality checks.
531
+
532
+ Methods::
533
+
534
+ __getitem__(index: typing.SupportsIndex | slice) ->
535
+ T | 'SliceableDeque[T]':
536
+ Returns the item or slice at the given index.
537
+ __eq__(other: typing.Any) -> bool:
538
+ Checks equality with another object, allowing for comparison with
539
+ lists, tuples, and sets.
540
+ pop(index: int = -1) -> T:
541
+ Removes and returns the item at the given index. Only supports
542
+ index 0 and the last index.
543
+ """
544
+
545
+ @typing.overload
546
+ def __getitem__(self, index: typing.SupportsIndex) -> T:
547
+ """Overload: an integer index returns a single item."""
548
+
549
+ @typing.overload
550
+ def __getitem__(self, index: slice) -> 'SliceableDeque[T]':
551
+ """Overload: a slice returns a new ``SliceableDeque``."""
552
+
553
+ def __getitem__(
554
+ self, index: typing.SupportsIndex | slice
555
+ ) -> T | 'SliceableDeque[T]':
556
+ """
557
+ Return the item or slice at the given index.
558
+
559
+ Args:
560
+ index (typing.SupportsIndex | slice): The index or
561
+ slice to retrieve.
562
+
563
+ Returns:
564
+ T | 'SliceableDeque[T]': The item or slice at the
565
+ given index.
566
+
567
+ Examples:
568
+ >>> d = SliceableDeque[int]([1, 2, 3, 4, 5])
569
+ >>> d[1:4]
570
+ SliceableDeque([2, 3, 4])
571
+
572
+ >>> d = SliceableDeque[str](['a', 'b', 'c'])
573
+ >>> d[-2:]
574
+ SliceableDeque(['b', 'c'])
575
+ """
576
+ if isinstance(index, slice):
577
+ start, stop, step = index.indices(len(self))
578
+ return self.__class__(self[i] for i in range(start, stop, step))
579
+ else:
580
+ return super().__getitem__(index)
581
+
582
+ def __eq__(self, other: typing.Any) -> bool:
583
+ """
584
+ Checks equality with another object, allowing for comparison with
585
+ lists, tuples, and sets.
586
+
587
+ Args:
588
+ other (typing.Any): The object to compare with.
589
+
590
+ Returns:
591
+ bool: True if the objects are equal, False otherwise.
592
+ """
593
+ if isinstance(other, list):
594
+ return list(self) == other
595
+ elif isinstance(other, tuple):
596
+ return tuple(self) == other
597
+ elif isinstance(other, set):
598
+ return set(self) == other
599
+ else:
600
+ return super().__eq__(other)
601
+
602
+ def pop(self, index: int = -1) -> T:
603
+ """
604
+ Removes and returns the item at the given index. Only supports index 0
605
+ and the last index.
606
+
607
+ Args:
608
+ index (int, optional): The index of the item to remove. Defaults to
609
+ -1.
610
+
611
+ Returns:
612
+ T: The removed item.
613
+
614
+ Raises:
615
+ IndexError: If the index is not 0 or the last index.
616
+
617
+ Examples:
618
+ >>> d = SliceableDeque([1, 2, 3])
619
+ >>> d.pop(0)
620
+ 1
621
+ >>> d.pop()
622
+ 3
623
+ """
624
+ if index == 0:
625
+ return super().popleft()
626
+ elif index in {-1, len(self) - 1}:
627
+ return super().pop()
628
+ else:
629
+ raise IndexError(
630
+ 'Only index 0 and the last index (`N-1` or `-1`) are supported'
631
+ )
632
+
633
+
634
+ if __name__ == '__main__':
635
+ import doctest
636
+
637
+ doctest.testmod()