-
Notifications
You must be signed in to change notification settings - Fork 0
/
classes.py
2141 lines (1761 loc) · 61.6 KB
/
classes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""A bunch of classes I made."""
import sys, types, collections, itertools, re, math, operator, inspect
import functools, io, textwrap, enum, reprlib, ctypes
import functools2
from functools2 import typechecking, autocurrying, Sentinel
from collections import OrderedDict, defaultdict
import collections.abc as cabc
_empty = Sentinel('<empty>')
class HashlessMap(cabc.MutableMapping):
"""Input key/value pairs as tuples.
HashlessMap([('a', 1), ('b', 2)])
HashlessMap(('a', 1), ('b', 2))
HashlessMap({'a': 1}, b=2) -> HashlessMap([('a', 1), ('b', 2)])
"""
def __init__(self, *args, **kwargs):
self._keys = []
self._values = []
self.update(*args, **kwargs)
def update(self, *args, **kwargs):
if len(args) == 1:
obj = args[0]
if isinstance(obj, cabc.Mapping):
items = obj.items()
elif hasattr(obj, 'keys'):
items = ((key, obj[key]) for key in obj.keys())
elif len(obj) == 2:
try:
items = [(key, value) for key, value in obj]
except (TypeError, ValueError):
items = args
else: items = obj
else: items = args
for key, value in itertools.chain(items, kwargs.items()):
self[key] = value
def __getitem__(self, key):
try:
return self._values[self._keys.index(key)]
except ValueError:
raise KeyError('Key not in map.') from None
def __setitem__(self, key, value):
try:
self._values[self._keys.index(key)] = value
except ValueError:
self._keys.append(key)
self._values.append(value)
def __delitem__(self, key):
try:
index = self._keys.index(key)
del self._keys[index], self._values[index]
except ValueError:
raise KeyError('Key not in map.') from None
def __contains__(self, key):
return key in self._keys
def __len__(self):
return len(self._keys)
def __iter__(self):
yield from self._keys
@reprlib.recursive_repr()
def __repr__(self):
return 'HashlessMap({})'.format(list(self.items()))
def __str__(self):
return '{{{}}}'.format(
', '.join('{!r}: {!r}'.format(k, v) for k, v in self.items()))
def keys(self):
return HashlessMapKeys(self)
def items(self):
return HashlessMapItems(self)
def values(self):
return HashlessMapValues(self)
class HashlessMapKeys(cabc.KeysView):
def __iter__(self):
yield from self._mapping._keys
def __contains__(self, key):
return key in self._mapping._keys
def __repr__(self):
return '<{}({})>'.format(type(self).__name__, list(self))
class HashlessMapItems(cabc.ItemsView):
def __iter__(self):
yield from zip(self._mapping._keys, self._mapping._values)
def __repr__(self):
return '<{}({})>'.format(type(self).__name__, list(self))
class HashlessMapValues(cabc.ValuesView):
def __iter__(self):
yield from self._mapping._values
def __contains__(self, value):
return value in self._mapping._values
def __repr__(self):
return '<{}({})>'.format(type(self).__name__, list(self))
class DictNS(dict):
"""A dictionary useable as a namespace."""
def __init__(self, *args, **kwargs):
self.__dict__ = self
super().__init__(*args, **kwargs)
class DictNS2(dict):
"""Alternate implementation of dictionary namespace."""
__slots__ = ()
def __getattr__(self, name):
try:
return self[name]
except KeyError as e:
raise AttributeError(*e.args) from None
def __setattr__(self, name, value):
self[name]=value
def __delattr__(self, name):
try:
del self[name]
except KeyError as e:
raise AttributeError(*e.args) from None
@property
def __dict__(self):
return self
class MappingNS(cabc.MutableMapping):
"""A normal object namespace with a mapping interface."""
def __init__(self, *args, **kwargs):
vars(self).update(*args, **kwargs)
def __getitem__(self, name):
return vars(self)[name]
def __setitem__(self, name, value):
vars(self)[name] = value
def __delitem__(self, name):
del vars(self)[name]
def __iter__(self):
return iter(vars(self))
def __len__(self):
return len(vars(self))
def __repr__(self):
return repr(vars(self))
class AutoAttr:
def __getattr__(self, name):
value = type(self)()
setattr(self, name, value)
return value
class AutoDict(dict):
def __missing__(self, key):
value = type(self)()
self[key] = value
return value
def AutoDefDict(*args, **kwargs):
return defaultdict(AutoDefDict, *args, **kwargs)
class AutoDictNS(DictNS, AutoDict, AutoAttr):
pass
def _safe_super(typ, obj):
return super(typ, obj) if isinstance(obj, typ) else obj
class DotDict(AutoDict):
def __init__(__self, *args, **kwargs):
super().__init__()
__self.update(*args, **kwargs)
update = cabc.MutableMapping.update
def __getitem__(self, key):
return self.get_by_keys(key.split('.'))
def __setitem__(self, key, value):
keys = key.split('.')
dct = self.get_by_keys(keys[:-1])
_safe_super(__class__, dct).__setitem__(keys[-1], value)
def __delitem__(self, key):
keys = key.split('.')
dct = self.get_by_keys(keys[:-1], False)
_safe_super(__class__, dct).__delitem__(keys[-1])
def __contains__(self, key):
missing = object()
return self.get_by_keys(key.split('.'), default=missing) is not missing
def get(self, key, default=None):
return self.get_by_keys(key.split('.'), default=default)
def setdefault(self, key, default=None):
keys = key.split('.')
dct = self.get_by_keys(keys[:-1])
return _safe_super(__class__, dct).setdefault(keys[-1], default)
def pop(self, key, default=_empty):
if default is not _empty:
try:
return self.pop(key)
except KeyError:
return default
keys = key.split('.')
dct = self.get_by_keys(keys[:-1], False)
return _safe_super(__class__, dct).pop(keys[-1])
def get_by_keys(self, keys, create=True, default=_empty):
if default is not _empty:
create = False
value = self
for key in keys:
if create or _safe_super(__class__, value).__contains__(key):
value = _safe_super(__class__, value).__getitem__(key)
elif default is not _empty:
return default
else:
raise KeyError(key)
return value
class DotDictNS(DotDict, DictNS, AutoAttr):
pass
class LazyList(list):
"""List that updates itself lazily from an iterator."""
def __init__(self, it=()):
self._iter = iter(it)
def __iter__(self):
yield from super().__iter__()
for obj in self._iter:
super().append(obj)
yield obj
def fill(self):
for obj in self._iter:
super().append(obj)
def fill_to(self, n):
if n < 0:
return self.fill()
m = max(n - len(self), 0)
for obj in itertools.islice(self._iter, m):
super().append(obj)
def __getitem__(self, index):
self.fill_to(index + 1 if index >= 0 else -1)
return super().__getitem__(index)
def __setitem__(self, index, value):
self.fill_to(index + 1 if index >= 0 else -1)
super().__setitem__(index, value)
def __delitem__(self, index):
self.fill_to(index + 1 if index >= 0 else -1)
super().__delitem__(index)
def append(self, object):
self.fill()
super().append(object)
def extend(self, iterable):
self.fill()
super().extend(iterable)
def insert(self, index, object):
self.fill_to(index)
super().insert(index, object)
def pop(self, index=-1):
self.fill_to(index + 1 if index >= 0 else -1)
return super().pop(index)
class Caching:
_cache = {}
def __new__(cls, key):
try:
return cls._cache[key]
except KeyError:
inst = super().__new__(cls)
cls._cache[key] = inst
return inst
class CustomMagic:
def __setattr__(self, name, value):
# if name is a "magic" method
# and there is not already a property asigned to it
if re.match(r'^__\w+__$', name) and \
isinstance(value, types.FunctionType) and \
not isinstance(getattr(type(self), name, None), property):
def fget(self):
return vars(self)[name]
def fset(self, value):
vars(self)[name] = value
def fdel(self):
del vars(self)[name]
try:
setattr(type(self), name, property(fget, fset, fdel))
except AttributeError: pass
super().__setattr__(name, value)
### Convert list of bits to int and vice-versa. ###
def int_to_bits(num):
bits = []
while num > 0:
bits.append(num & 1)
num >>= 1
bits.reverse()
return bits
def bits_to_int(bits):
num = 0
for bit in bits:
num = (num << 1) | bool(bit)
return num
class Bits(cabc.Sequence):
def __init__(self, value, length=None, endian='big'):
if isinstance(value, str):
self.value = int(value, 2)
if isinstance(value, int):
if value < 0:
raise ValueError("unsigned integers only")
self.value = value
l = value.bit_length()
elif isinstance(value, cabc.ByteString):
self.value = int.from_bytes(value, endian)
l = 8 * len(value)
else:
self.value = 0
for i, bit in enumerate(value):
self.value |= bool(bit) << i
l = len(value)
self.length = length if length is not None else l
def __len__(self):
return self.length
def __getitem__(self, idx):
l = self.length
if idx < 0:
idx += l
if idx < 0 or idx >= l:
raise IndexError('bit index out of range')
return self.value >> idx & 1
def __setitem__(self, idx, value):
l = self.length
if idx < 0:
idx += l
if idx < 0 or idx >= l:
raise IndexError('bit index out of range')
self.value = self.value & ~(1 << idx) | (value << idx)
self.value ^= (-value ^ self.value) & (1 << idx)
def __iter__(self):
num = self.value
for i in range(self.length):
yield num >> i & 1
def __int__(self):
return self.value
def __index__(self):
return self.value
def __eq__(self, other):
if isinstance(other, Bits):
return self.value == other.value and self.length == other.length
return False
def __repr__(self):
return 'Bits({})'.format(list(self))
class IterProxy(cabc.Iterable):
def each(self, attr):
return type(self)(getattr(obj, attr) for obj in self)
def __getattr__(self, name):
return self.each(name)
def __call__(self, *args, **kwargs):
return type(self)(obj(*args, **kwargs) for obj in self)
class WrapperProxy(IterProxy):
def __init__(self, it):
self._iter = it
def __iter__(self):
return iter(self._iter)
def __getattr__(self, name):
try:
return getattr(self._iter, name)
except AttributeError:
return self.each(name)
def __getitem__(self, index):
if isinstance(index, slice):
return type(self)(self._iter[index])
return self._iter[index]
def __repr__(self):
return 'WrapperProxy({})'.format(self._iter)
class ListProxy(list, IterProxy):
def __repr__(self):
return 'ListProxy({})'.format(super().__repr__())
class PropagatingNone:
_inst = None
def __new__(cls):
if cls._inst is None:
cls._inst = super().__new__(cls)
return cls._inst
def __eq__(self, other):
return other == None
def __hash__(self):
return hash(None)
def __bool__(self):
return False
def __getattr__(self, name):
return self
def __call__(self, *args, **kwargs):
return self
PNone = PropagatingNone()
class FakeFunc:
def __init__(self, name='', body=None, returnv=None,
params=(), defaults=None, starargs=None, starkws=None):
self.name = name
self.code = body and compile(body, '<string>', 'exec') or None
self.returnc = returnv and compile(returnv, '<string>', 'eval') or None
self.params = tuple(params)
self.defaults = dict(defaults or {})
self.starargs = starargs
self.starkws = starkws
def __call__(self, *args, **kwargs):
fargs = {}
others = args[len(self.params):]
if self.starargs:
fargs[self.starargs] = others
elif others:
raise TypeError("{} takes at most {} argument(s)".format(
self.name, len(self.params)-len(self.defaults)))
otherkws = {k: v for k, v in kwargs.items() if k not in self.params}
if self.starkws:
fargs[self.starkws] = otherkws
elif otherkws:
raise TypeError("{} doesn't expect keyword argument '{}'".format(
self.name, list(otherkws)[0]))
fargs.update(self.defaults)
fargs.update(zip(self.params, args))
fargs.update({k: v for k, v in kwargs.items() if k in self.params})
if fargs.keys() < set(self.params):
raise TypeError('{} requires at least {} arguments.'.format(
self.name, len(self.params)-len(self.defaults)))
if self.code: exec(self.code, globals(), fargs)
if self.returnc: return eval(self.returnc, globals(), fargs)
## alternative implementation for getting params
##for i, p in enumerate(self.params):
## try:
## fargs[p] = kwargs[p]
## except KeyError:
## try:
## fargs[p] = args[i]
## except IndexError:
## try:
## fargs[p] = self.defaults[p]
## except KeyError:
## raise TypeError("{} requires at least {} argument(s)."
## .format(self.name, len(self.params)-len(self.defaults))) from None
class SeqDict(OrderedDict):
def __getitem__(self, key):
try:
key = list(self)[key]
except TypeError:
pass
return super().__getitem__(key)
def __setitem__(self, key, value):
try:
key = list(self)[key]
except TypeError:
pass
super().__setitem__(key, value)
def __delitem__(self, key):
try:
key = list(self)[key]
except TypeError:
pass
super().__delitem__(key)
## def __init__(self, *args, **kwargs):
## self._keys = []
## super().__init__(*args, **kwargs)
##
## def __getitem__(self, key):
## try:
## key = self._keys[key]
## except TypeError:
## pass
## return super().__getitem__(key)
##
## def __setitem__(self, key, value):
## try:
## key = self._keys[key]
## except TypeError:
## pass
## if key not in self:
## self._keys.append(key)
## super().__setitem__(key, value)
class methoddescriptor:
def __init__(self, func):
self.__func__ = func
def __get__(self, obj, typ=None):
if obj: return types.MethodType(self.__func__, obj)
return self.__func__
class InheritingDictMeta(type):
## @classmethod
## def get_prepare_type(cls, typ, typ2):
## if issubclass(typ, typ2):
## return typ
## return type('_CustomDict', (typ, typ2), {})
## @classmethod
## def get_prepare_type(cls, curcls, dicttype, *args, **kwargs):
## dicttype2 = type(super(curcls, cls).__prepare__(*args, **kwargs))
## if issubclass(dicttype, dicttype2):
## return dicttype
## return type('_CustomDict', (dicttype, dicttype2), {})
@classmethod
def __prepare__(cls, name, bases, **kwargs):
dicttypes = []
for base in cls.__mro__:
try:
typ = vars(base)['_dicttype']
except KeyError:
continue
if typ not in dicttypes:
dicttypes.append(typ)
if not dicttypes:
return {}
if len(dicttypes) == 1:
return dicttypes[0]()
return type('_CustomDict', tuple(dicttypes), {})()
class overloading:
def __init__(self, *funcs):
if not funcs: raise TypeError('At least one function required.')
self.funcs = list(funcs)
functools2.update_wrapper_signature(self, funcs[0])
@classmethod
def auto(cls, func):
try:
name = func.__name__
except AttributeError:
name = func.__func__.__name__
clsvars = sys._getframe(1).f_locals
obj = clsvars.get(name)
if isinstance(obj, overloading):
return obj.overload(func)
return cls(func)
def overload(self, *funcs):
if not funcs: raise TypeError('At least one function required.')
self.funcs += funcs
return self
def __call__(self, *args, **kwargs):
err = None
for func in self.funcs:
try:
return func(*args, **kwargs)
except TypeError as e:
err = e
raise TypeError('No function with matching signature.') from err
def __get__(self, obj, typ=None):
return OverloadedMethod(self, obj, typ)
class OverloadedMethod:
def __init__(self, overloading, obj, typ):
self.overloading = overloading
self.funcs = overloading.funcs
self.obj = obj
self.typ = typ
def __call__(self, *args, **kwargs):
err = None
for func in self.funcs:
try:
return func.__get__(self.obj, self.typ)(*args, **kwargs)
except TypeError as e:
err = e
raise TypeError('No function with matching signature.') from err
class _OverloadingDict(dict):
def __setitem__(self, key, value):
if isinstance(value, (types.FunctionType, classmethod, staticmethod)):
obj = self.get(key)
if isinstance(obj, overloading):
value = obj.overload(value)
else:
value = overloading(value)
super().__setitem__(key, value)
class OverloadingMeta(InheritingDictMeta):
_dicttype = _OverloadingDict
## @classmethod
## def __prepare__(cls, name, bases):
## return cls.get_prepare_type(_OverloadingDict,
## type(super().__prepare__(name, bases)))()
class OverloadingBase(metaclass=OverloadingMeta):
pass
class _TypeCheckingDict(dict):
def __setitem__(self, key, value):
if isinstance(value, types.FunctionType):
if not hasattr(value, '_typechecking'):
value = typechecking(value)
elif isinstance(value, classmethod):
value = classmethod(typechecking(value.__func__))
elif isinstance(value, staticmethod):
value = staticmethod(typechecking(value.__func__))
super().__setitem__(key, value)
class TypeCheckingMeta(InheritingDictMeta):
_dicttype = _TypeCheckingDict
## @classmethod
## def __prepare__(cls, name, bases):
## return cls.get_prepare_type(_TypeCheckingDict,
## type(super().__prepare__(name, bases)))()
class TypeCheckingBase(metaclass=TypeCheckingMeta):
pass
class OverloadingTypeCheckingMeta(TypeCheckingMeta, OverloadingMeta):
pass
class OverloadingTypeChecking(metaclass=OverloadingTypeCheckingMeta):
pass
try:
from implicitself import implicit_self, implicit_this
except ImportError:
pass
else:
class _ImplicitSelfDict(dict):
def __setitem__(self, key, value):
if isinstance(value, types.FunctionType):
value = implicit_self(value)
super().__setitem__(key, value)
class ImplicitSelfMeta(InheritingDictMeta):
_dicttype = _ImplicitSelfDict
## @classmethod
## def __prepare__(cls, name, bases):
## return cls.get_prepare_type(__class__, _ImplicitSelfDict, name, bases)()
class ImplicitSelfBase(metaclass=ImplicitSelfMeta):
pass
class _ImplicitThisDict(dict):
def __setitem__(self, key, value):
if isinstance(value, types.FunctionType):
value = implicit_this(value)
super().__setitem__(key, value)
class ImplicitThisMeta(InheritingDictMeta):
_dicttype = _ImplicitThisDict
## @classmethod
## def __prepare__(cls, name, bases):
## return cls.get_prepare_type(__class__, _ImplicitThisDict, name, bases)()
class ImplicitThisBase(metaclass=ImplicitThisMeta):
pass
class JavaClassMeta(ImplicitThisMeta, OverloadingTypeCheckingMeta):
pass
class JavaClass(metaclass=JavaClassMeta):
pass
class AbstractSet:
def __init__(self, predicate):
if isinstance(predicate, AbstractSet):
self.predicate = predicate.predicate
elif callable(predicate):
self.predicate = predicate
elif isinstance(predicate, cabc.Container):
self.predicate = predicate.__contains__
else:
raise TypeError('argument must be callable or container')
def __contains__(self, obj):
return self.predicate(obj)
def __invert__(self):
pred = self.predicate
return AbstractSet(lambda obj: not pred(obj))
def __and__(self, other):
pred1 = self.predicate
pred2 = AbstractSet(other).predicate
return AbstractSet(lambda obj: pred1(obj) and pred2(obj))
def __or__(self, other):
pred1 = self.predicate
pred2 = AbstractSet(other).predicate
return AbstractSet(lambda obj: pred1(obj) or pred2(obj))
def __xor__(self, other):
pred1 = self.predicate
pred2 = AbstractSet(other).predicate
return AbstractSet(lambda obj: pred1(obj) ^ pred2(obj))
def __sub__(self, other):
pred1 = self.predicate
pred2 = AbstractSet(other).predicate
return AbstractSet(lambda obj: pred1(obj) and not pred2(obj))
# The set of all sets not members of themselves
russels_set = AbstractSet(lambda obj: isinstance(obj, cabc.Container)
and obj not in obj)
def frange(start, stop=None, step=1):
if stop is None:
start, stop = 0, start
count = start
while count < stop:
yield count
count += step
class FRange(cabc.Sequence):
def __init__(self, start, stop=None, step=1):
if stop is None:
start, stop = 0, start
self.start, self.stop, self.step = start, stop, step
def __iter__(self):
count = 0
i = self.start
while i < self.stop:
yield i
count += 1
i = self.start + self.step * count
def __len__(self):
return math.ceil((self.stop - self.start) / self.step)
def __getitem__(self, index):
if index < 0:
index += len(self)
value = self.start + self.step * index
if value < self.start or value >= self.stop:
raise IndexError(index)
return value
def __contains__(self, value):
if value < self.start or value >= self.stop:
return False
return (value - self.start) % self.step == 0
class FollowDescriptors:
def __getattribute__(self, name):
value = super().__getattribute__(name)
if hasattr(type(value), '__get__'):
return value.__get__(self, type(self))
else:
return value
def __setattr__(self, name, value):
try:
curvalue = super().__getattribute__(name)
except AttributeError:
return super().__setattr__(name, value)
if hasattr(type(curvalue), '__set__'):
curvalue.__set__(self, value)
else:
super().__setattr__(name, value)
def __delattr__(self, name):
value = super().__getattribute__(name)
if hasattr(type(value), '__delete__'):
value.__delete__(self)
else:
super().__delattr__(name)
class SearchableDict(OrderedDict):
def __getitem__(self, key):
try:
return super().__getitem__(key)
except KeyError:
for k, v in self.items():
if k.startswith(key):
return v
raise KeyError
def search(self, key):
return SearchableDict((k,v) for k, v in self.items()
if k.startswith(key))
class Attr:
def __init__(self, name, field=None, readonly=False, deletable=False):
self.name = name
self.field = field or '_' + name
self.readonly = readonly
self.deletable = deletable
def __get__(self, obj, typ):
if obj is None:
return self
try:
return vars(obj)[self.field]
except KeyError:
raise AttributeError("'{}' is unset".format(self.name)) from None
def __set__(self, obj, val):
if self.readonly:
raise AttributeError("can't set '{}'".format(self.name))
vars(obj)[self.field] = val
def __delete__(self, obj):
if not self.deletable:
raise AttributeError("can't delete '{}'".format(self.name))
try:
del vars(obj)[self.field]
except KeyError:
raise AttributeError("'{}' is unset".format(self.name)) from None
class TypedAttr(Attr):
def __init__(self, name, typ, field=None, deletable=False):
super().__init__(name, field, deletable=deletable)
self.typ = typ
def __set__(self, obj, val):
if not isinstance(val, self.typ):
raise TypeError("'{}' must be of type {}".format(
self.name, self.typ.__name__))
super().__set__(obj, val)
class TypedDict(dict):
def __init__(self, *args, **kwargs):
self._types = dict(*args, **kwargs)
def __setitem__(self, key, value):
if key in self._types:
typ = self._types[key]
if not isinstance(value, typ):
raise TypeError("'{}' must be of type '{}'"
.format(key, typ.__name__))
super().__setitem__(key, value)
class TypedAttrs:
def __setattr__(self, name, value):
if name in self._types:
typ = self._types[name]
if not isinstance(value, typ):
raise TypeError("'{}' must be of type '{}'"
.format(name, typ.__name__))
super().__setattr__(name, value)
class MultiSet:
def __init__(self, *containers):
self.containers = list(containers)
def __iter__(self):
for cont in self.containers:
yield from cont
def __contains__(self, value):
return any(value in cont for cont in self.containers)
def __len__(self):
return sum(map(len, self.containers))
def __repr__(self):
return '{}({})'.format(type(self).__name__, ', '.join(
map(repr, self.containers)))
class MultiSeq(MultiSet, cabc.Sequence):
def __getitem__(self, index):
if index < 0:
index += len(self)
for seq in self.containers:
if index < len(seq):
return seq[index]
index -= len(seq)
raise IndexError
class MultiList(MultiSeq, cabc.MutableSequence):
def __setitem__(self, index, value):
if index < 0:
index += len(self)
for seq in self.containers:
if index < len(seq):
seq[index] = value
return
index -= len(seq)
raise IndexError
def __delitem__(self, index):
if index < 0:
index += len(self)
for seq in self.containers:
if index < len(seq):
del seq[index]
return
index -= len(seq)
raise IndexError
def insert(self, index, value):
l = len(self)
if index >= l:
self.append(value)
return
if index < 0:
index += l
for seq in self.containers:
if index <= len(seq):
seq.insert(index, value)
return
index -= len(seq)
def append(self, value):
self.containers[-1].append(value)
class Tree:
def __init__(self, *children):
self.parent = None
self.children = list(children)
for child in children:
if isinstance(child, Tree):
child.parent = self