-
Notifications
You must be signed in to change notification settings - Fork 7
/
utils.py
2654 lines (2151 loc) · 81.9 KB
/
utils.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
import os, sys, io, bisect, random, copy, collections, itertools, struct, array, re, traceback, hashlib, math, string, weakref, operator, heapq, time, json, tempfile
from datetime import datetime, timedelta, timezone
from functools import reduce, total_ordering, lru_cache
from copy import copy, deepcopy
from io import BytesIO, StringIO
from warnings import warn
from reprlib import recursive_repr
def _my_excepthook(type, value, tb):
obj = traceback.TracebackException(type, value, tb)
for hook in _my_excepthook.hooks:
hook(obj)
for line in obj.format():
print(line, file=sys.stderr, end="")
def add_traceback_hook(hook):
"""adds a hook to be called before printing a traceback, so that the hook can edit it freely"""
_my_excepthook.hooks.append(hook)
_my_excepthook.hooks = []
sys.excepthook = _my_excepthook
def eprint(*args, **kwargs):
"""like print, but prints to stderr"""
print(*args, file=sys.stderr, **kwargs)
def context_manager(method_name = "close"):
"""Adds __enter__/__exit__ support for a class, using a specified method_name as the 'close' method"""
def decorator(cls):
method = getattr(cls, method_name)
def __enter__(m):
return m
def __exit__(m, t, v, s):
method(m)
cls.__enter__ = __enter__
cls.__exit__ = __exit__
return cls
return decorator
def exec_def(name, code):
"""execute 'code' and extract a definition named 'name' from it"""
namespace = {}
exec(code, namespace)
return namespace[name]
def exec_script_by_path(path, name=None):
"""executes script at 'path', returning its module object"""
import importlib.util
script_spec = importlib.util.spec_from_file_location(default(name, path_basename_no_extension(path)), path_absolute(path))
script_mod = importlib.util.module_from_spec(script_spec)
script_spec.loader.exec_module(script_mod)
return script_mod
def import_from_script_by_path(path, *func_names):
"""executes script at 'path', importing the requested funcs from it - if they exist"""
script_mod = exec_script_by_path(path)
return tuple(getattr(script_mod, name, None) for name in func_names)
def typename(obj):
"""returns the name of the object's type"""
return type(obj).__name__
class Dynamic(object):
"""An anonymous dynamic class with keyword-args-style initialization"""
def __init__(__m_, **__kw_):
__m_.__dict__ = __kw_
@recursive_repr()
def __repr__(m):
contents = ", ".join(f"{k}={repr(v)}" for k, v in m.__dict__.items())
return f"{typename(m)}({contents})"
class DefaultDynamic(Dynamic):
"""Like Dynamic, but accessing an unknown key gives None"""
def __getattr__(m, name):
return None
def isdescriptor(obj):
"""Return whether the value is a descriptor"""
return hasattr(obj, "__get__") or hasattr(obj, "__set__") or hasattr(obj, "__del__")
class IncludeAttr:
"""When defining an Enum/Tuple/etc, forces the attribute to be included, despite having a private name or being a function/descriptor/..."""
def __init__(m, value):
m.value = value
class NoRenameAttr(IncludeAttr):
"""When defining an Enum/Tuple/etc, forces the attribute to be included and not be renamed, despite having a name ending in _"""
def __init__(m, value):
m.value = value
class ExcludeAttr:
"""When defining an Enum/Tuple/etc, forces the attribute to be excluded, despite not having a private name nad not being a function/descriptor/..."""
def __init__(m, value):
m.value = value
def _metaclass_collect_values(cls_dict, values, prefirst, next, with_aliases=True):
prev_value = prefirst
for key, value in default(values, cls_dict).items():
keep_key = False
if key.startswith("__") and key.endswith("__"):
continue
elif isinstance(value, IncludeAttr):
keep_key = isinstance(value, NoRenameAttr)
value = value.value
elif key.startswith("_") or callable(value) or isdescriptor(value) or isinstance(value, ExcludeAttr):
continue
elif value is ...:
value = next(prev_value)
prev_value = value
yield key, value
if key.endswith("_") and not keep_key:
yield key[:-1], value # yield "proper" name last, so it overrides the '_' name in reverse maps
def _metaclass_collect_fields(cls_dict, values):
fields = []
defaults = []
no_default = defaults # marker value, compare via 'is'
def next_no_default(_):
return no_default
for k, v in _metaclass_collect_values(cls_dict, values, None, next_no_default, with_aliases=False):
fields.append(k)
if v is not no_default:
defaults.append(v)
elif defaults:
raise Exception(f"Cannot specify required field {k} after optional fields")
return tuple(fields), tuple(defaults)
class EnumMetaclass(type):
def __new__(meta, cls_name, cls_bases, cls_dict, values=None):
if not cls_bases or Enum not in cls_bases:
return super().__new__(meta, cls_name, cls_bases, cls_dict)
# collect
enum_bases = tuple(base for base in cls_bases if base is not Enum and base.__class__ == EnumMetaclass)
def next_auto(prev):
if enum_bases:
raise Exception("Enum with bases must use explicit values") # TODO
if not isinstance(prev, (int, float)):
raise Exception(f"Cannot follow {prev} with ...")
return prev + 1
name_value_map = dict(_metaclass_collect_values(cls_dict, values, 0, next_auto))
full_name_value_map = name_value_map.copy() if enum_bases else name_value_map
for base in enum_bases:
full_name_value_map.update(base._values)
full_value_name_map = {v:k for k,v in full_name_value_map.items()}
# dict
def __init__(m, value):
if value in full_value_name_map:
m.value = value
elif value in full_name_value_map:
m.value = full_name_value_map[value]
else:
raise ValueError(f"{value} not value of {cls_name}")
def __eq__(m, other):
if m.__class__ != other.__class__:
return NotImplemented
return m.value == other.value
def __lt__(m, other):
if not isinstance(m, other.__class__) and not isinstance(other, m.__class__):
return NotImplemented
return m.value < other.value
def __str__(m):
return full_value_name_map[m.value]
def __repr__(m):
return f"{cls_name}.{full_value_name_map[m.value]}"
def __int__(m):
return m.value
def __hash__(m):
return hash(m.value)
enum_dict = {}
enum_dict["__init__"] = __init__
enum_dict["__eq__"] = __eq__
enum_dict["__lt__"] = __lt__
enum_dict["__str__"] = __str__
enum_dict["__repr__"] = __repr__
enum_dict["__int__"] = __int__
enum_dict["__hash__"] = __hash__
enum_dict["__slots__"] = ("value",)
enum_dict["_values"] = full_name_value_map
for k, v in cls_dict.items():
if isinstance(v, ExcludeAttr):
v = v.value
if k in name_value_map:
continue
elif k == "__slots__":
enum_dict[k] = enum_dict[k] + (v if isinstance(v, tuple) else (v,))
elif k in enum_dict:
raise Exception(f"Cannot set {k} in Enum (but can override in inherited classes)")
else:
enum_dict[k] = v
enum_class = super().__new__(meta, cls_name, cls_bases, enum_dict)
for k, v in name_value_map.items():
setattr(enum_class, k, enum_class(v))
enum_class = total_ordering(enum_class)
return enum_class
class Enum(metaclass=EnumMetaclass):
"""If a class has Enum as a baseclass, it's transformed into an enum.
All non-private attributes of the class other than functions and descriptors become enum members.
Atributes with a value of ... receive values automatically.
Inherited classes behave like regular classes unless they have Enum as a direct baseclass.
Advanced: ExcludeAttr/IncludeAttr, values keyword parameter
Atributes with a name ending with _ can be referred to without the _.
"""
class BitmaskMetaclass(type):
def __new__(meta, cls_name, cls_bases, cls_dict, values=None):
if not cls_bases or Bitmask not in cls_bases:
return super().__new__(meta, cls_name, cls_bases, cls_dict)
# collect
bitmask_bases = tuple(base for base in cls_bases if base is not Bitmask and base.__class__ == BitmaskMetaclass)
def next_auto(prev):
if bitmask_bases:
raise Exception("Bitmasks with bases must use explicit values") # TODO
if not isinstance(prev, int) or (prev != 0 and not is_pow2(prev)):
raise Exception(f"Cannot follow {prev} with ...")
return prev << 1 if prev != 0 else 1
name_mask_map = dict(_metaclass_collect_values(cls_dict, values, 0, next_auto))
full_name_mask_map = name_mask_map.copy() if bitmask_bases else name_mask_map
for base in bitmask_bases:
full_name_mask_map.update(base._fields)
full_mask_name_map = {v:k for k,v in full_name_mask_map.items()}
full_mask = reduce(lambda x,y:x|y, full_mask_name_map.keys(), 0)
# dict
def __init__(m, value = None, **kwargs):
if value is None:
m.value = 0
elif isinstance(value, int) and (value & full_mask) == value:
m.value = value
elif isinstance(value, str) and value in full_name_mask_map:
m.value = full_name_mask_map[value]
elif isinstance(value, m.__class__):
m.value = value.value
elif isinstance(value, (tuple, list)):
m.value = reduce(lambda x,y:x|y, (full_name_mask_map[part] for part in value), 0)
else:
raise ValueError(f"{value} not value of {cls_name}")
if kwargs:
for key, value in kwargs.items():
setattr(m, key, value)
def __eq__(m, other):
if m.__class__ != other.__class__:
return NotImplemented
return m.value == other.value
def __hash__(m):
return hash(m.value)
def __str__(m):
if m.value:
values = []
for mask, name in full_mask_name_map.items():
if m.value & mask:
values.append(name)
return ",".join(values)
else:
return ""
def __repr__(m):
if m.value:
values = []
for mask, name in full_mask_name_map.items():
if m.value & mask:
values.append(f"{cls_name}.{name}")
return " | ".join(values)
else:
return f"{cls_name}(0)"
def __int__(m):
return m.value
def __bool__(m):
return m.value != 0
def __and__(m, other):
if m.__class__ != other.__class__:
return NotImplemented
return m.__class__(m.value & other.value)
def __or__(m, other):
if m.__class__ != other.__class__:
return NotImplemented
return m.__class__(m.value | other.value)
def __xor__(m, other):
if m.__class__ != other.__class__:
return NotImplemented
return m.__class__(m.value ^ other.value)
class no_bits_property:
def __init__(m, mask):
m.mask = mask
def __get__(m, obj, cls):
if obj is None:
return cls(m.mask)
else:
raise AttributeError()
def __set__(m, obj, value):
raise AttributeError()
class bit_property:
def __init__(m, mask):
m.mask = mask
def __get__(m, obj, cls):
if obj is None:
return cls(m.mask)
else:
return bool(obj.value & m.mask)
def __set__(m, obj, value):
if value:
obj.value |= m.mask
else:
obj.value &= ~m.mask
class bitfield_property:
def __init__(m, mask):
m.mask = mask
m.shift = count_trailing_zero_bits(mask)
def __get__(m, obj, cls):
if obj is None:
return cls(m.mask)
else:
return (obj.value & m.mask) >> m.shift
def __set__(m, obj, value):
obj.value = (obj.value & ~m.mask) | ((value << m.shift) & m.mask)
class typed_bitfield_property:
def __init__(m, mask, type):
m.mask, m.type = mask, type
m.shift = count_trailing_zero_bits(mask)
def __get__(m, obj, cls):
if obj is None:
return cls(m.mask)
else:
return m.type((obj.value & m.mask) >> m.shift)
def __set__(m, obj, value):
obj.value = (obj.value & ~m.mask) | ((int(value) << m.shift) & m.mask)
bitmask_dict = {}
bitmask_dict["__init__"] = __init__
bitmask_dict["__eq__"] = __eq__
bitmask_dict["__hash__"] = __hash__
bitmask_dict["__str__"] = __str__
bitmask_dict["__repr__"] = __repr__
bitmask_dict["__int__"] = __int__
bitmask_dict["__nonzero__"] = __bool__
bitmask_dict["__bool__"] = __bool__
bitmask_dict["__and__"] = __and__
bitmask_dict["__or__"] = __or__
bitmask_dict["__xor__"] = __xor__
bitmask_dict["__slots__"] = ("value",)
bitmask_dict["_fields"] = full_name_mask_map
annots = cls_dict.get("__annotations__", None)
for name, mask in name_mask_map.items():
if annots and name in annots:
bitmask_dict[name] = typed_bitfield_property(mask, annots[name])
elif mask == 0:
bitmask_dict[name] = no_bits_property(mask)
elif is_pow2(mask):
bitmask_dict[name] = bit_property(mask)
else:
bitmask_dict[name] = bitfield_property(mask)
for k, v in cls_dict.items():
if isinstance(v, ExcludeAttr):
v = v.value
if k in name_mask_map:
continue
elif k == "__slots__":
bitmask_dict[k] = bitmask_dict[k] + (v if isinstance(v, tuple) else (v,))
elif k in bitmask_dict:
raise Exception(f"Cannot set {k} in Bitmask (but can override in inherited classes)")
else:
bitmask_dict[k] = v
return super().__new__(meta, cls_name, cls_bases, bitmask_dict)
class Bitmask(metaclass=BitmaskMetaclass):
"""If a class has Bitmask as a baseclass, it's transformed into a bitmask.
All non-private attributes of the class other than functions and descriptors become bitmask fields.
Atributes with a value of ... receive bits automatically.
A bitmask is like a struct, but with its fields mapped into a single bitmask integer.
Bitmasks can also be manipulated via: & | ^
Inherited classes behave like regular classes unless they have Bitmask as a direct baseclass.
Advanced: ExcludeAttr/IncludeAttr, values keyword parameter
Atributes with a name ending with _ can be referred to without the _.
"""
class TupleMetaclass(type):
def __new__(meta, cls_name, cls_bases, cls_dict, values=None):
if not cls_bases or cls_bases == (tuple,) or Tuple not in cls_bases:
return super().__new__(meta, cls_name, cls_bases, cls_dict)
# collect
tuple_bases = tuple(base for base in cls_bases if base is not Tuple and base.__class__ == TupleMetaclass)
fields, defaults = _metaclass_collect_fields(cls_dict, values)
if tuple_bases:
if defaults:
raise Exception("Cannot use defaults with bases")
all_fields = sum((base._fields for base in tuple_bases), ()) + fields
else:
all_fields = fields
# dict
all_fields_str = ', '.join(all_fields)
all_fields_tupstr = all_fields_str + ("," if len(all_fields) == 1 else "")
new_def = f"def __new__(__cls, {all_fields_str}):\n"
new_def += f" return tuple.__new__(__cls, ({all_fields_tupstr}))\n"
__new__ = exec_def("__new__", new_def)
__new__.__defaults__ = defaults
def __reduce_ex__(m, proto):
return (m.__new__, (m.__class__, *m))
@recursive_repr()
def __repr__(m):
contents = ", ".join(f"{f}={repr(getattr(m, f))}" for f in m._fields)
return f"{cls_name}({contents})"
def _replace(m, **changes):
return m.__class__(*map(changes.pop, m._fields, m))
tuple_dict = {}
tuple_dict["__new__"] = __new__
tuple_dict["__reduce_ex__"] = __reduce_ex__
tuple_dict["__repr__"] = __repr__
tuple_dict["__slots__"] = () # fields come from tuple
tuple_dict["_replace"] = _replace
tuple_dict["_fields"] = all_fields
start = len(all_fields) - len(fields)
for i, field in enumerate(fields):
tuple_dict[field] = property(operator.itemgetter(start + i))
fields_set = set(fields)
for k, v in cls_dict.items():
if isinstance(v, ExcludeAttr):
v = v.value
if k in fields_set:
continue
elif k == "__slots__":
tuple_dict[k] = tuple_dict[k] + (v if isinstance(v, tuple) else (v,))
elif k in tuple_dict:
raise Exception(f"Cannot set {k} in Tuple (but can override in inherited classes)")
else:
tuple_dict[k] = v
return super().__new__(meta, cls_name, cls_bases, tuple_dict)
class Tuple(tuple, metaclass=TupleMetaclass):
"""If a class has Tuple as a baseclass, it's transformed into a named tuple.
All non-private attributes of the class other than functions and descriptors become tuple fields.
Atributes with a value of ... are required, otherwise - optional with the given default value.
The tuple behaves similarly to collections.namedtuple
Inherited classes behave like regular classes unless they have Tuple as a direct baseclass.
Advanced: ExcludeAttr/IncludeAttr, values keyword parameter
Atributes with a name ending with _ can be referred to without the _.
"""
class StructMetaclass(type):
def __new__(meta, cls_name, cls_bases, cls_dict, values=None):
if not cls_bases or Struct not in cls_bases:
return super().__new__(meta, cls_name, cls_bases, cls_dict)
# collect
struct_bases = tuple(base for base in cls_bases if base is not Struct and base.__class__ == StructMetaclass)
fields, defaults = _metaclass_collect_fields(cls_dict, values)
if struct_bases:
if defaults:
raise Exception("Cannot use defaults with bases")
all_fields = sum((base._fields for base in struct_bases), ()) + fields
else:
all_fields = fields
# dict
init_def = f"def __init__(__m, {', '.join(all_fields)}):\n"
for field in all_fields:
init_def += f" __m.{field} = {field}\n"
if not all_fields:
init_def += " pass"
__init__ = exec_def("__init__", init_def)
__init__.__defaults__ = defaults
@recursive_repr()
def __repr__(m):
contents = ", ".join(f"{f}={repr(getattr(m, f))}" for f in m._fields)
return f"{cls_name}({contents})"
# note - equality is by-identity (unless option to control is added?)
struct_dict = {}
struct_dict["__init__"] = __init__
struct_dict["__repr__"] = __repr__
struct_dict["__slots__"] = fields
struct_dict["_fields"] = all_fields
fields_set = set(fields)
for k, v in cls_dict.items():
if isinstance(v, ExcludeAttr):
v = v.value
if k in fields_set:
continue
elif k == "__slots__":
struct_dict[k] = struct_dict[k] + (v if isinstance(v, tuple) else (v,))
elif k in struct_dict:
raise Exception(f"Cannot set {k} in Struct (but can override in inherited classes)")
else:
struct_dict[k] = v
return super().__new__(meta, cls_name, cls_bases, struct_dict)
class Struct(metaclass=StructMetaclass):
"""If a class has Struct as a baseclass, it's transformed into a struct.
All non-private attributes of the class other than functions and descriptors become struct fields.
Atributes with a value of ... are required, otherwise - optional with the given default value.
A struct is like a mutable named tuple, except equality goes by identity.
Inherited classes behave like regular classes unless they have Struct as a direct baseclass.
Advanced: ExcludeAttr/IncludeAttr, values keyword parameter
Atributes with a name ending with _ can be referred to without the _.
"""
def SymbolClass(name):
"""Create a class with the given name that returns cached symbols when invoked"""
class cls(object):
__slots__ = 'value'
cache = {}
def __new__(cls, value):
ident = cls.cache.get(value)
if ident is None:
ident = super().__new__(cls)
ident.value = value
cls.cache[value] = ident
return ident
def __str__(m):
return str(m.value)
def __bytes__(m):
return bytes(m.value)
def __repr__(m):
return f"`{m.value}"
cls.__name__ = name
return cls
Symbol = SymbolClass("Symbol")
class classproperty(object):
"""Method decorator that turns it into a read-only class property"""
def __init__(m, func):
m.getter = func
def __get__(m, _, cls):
return m.getter(cls)
# must be read-only, sadly
class staticproperty(object):
"""Method decorator that turns it into a read-only static property"""
def __init__(m, func):
m.getter = func
def __get__(m, _, cls):
return m.getter()
# must be read-only, sadly
class writeonly_property(object):
"""Method decorator that turns it into a write-only property"""
def __init__(m, func):
m.func = func
def __set__(m, obj, value):
return m.func(obj, value)
# reminder to self - if you want a "default property", aka one that has a default value but is settable, use a class field
class lazy_property(object):
"""Method decorator that turns it into a lazily-evaluated property"""
def __init__(m, func):
m.func = func
def __get__(m, obj, cls):
if obj is None:
return m
else:
value = m.func(obj)
obj.__dict__[m.func.__name__] = value # won't be called again for this obj
return value
@staticmethod
def is_set(obj, name):
return name in obj.__dict__
@staticmethod
def clear(obj, name):
obj.__dict__.pop(name, None)
class lazy_classproperty(object):
"""Method decorator that turns it into a lazily-evaluated class property"""
def __init__(m, func):
m.func = func
def __get__(m, _, cls):
value = m.func(cls)
setattr(cls, m.func.__name__, value) # won't be called again for this obj
return value
class lazy_staticproperty(object):
"""Method decorator that turns it into a lazily-evaluated static property"""
def __init__(m, func):
m.func = func
def __get__(m, _, cls):
value = m.func()
setattr(cls, m.func.__name__, value) # won't be called again for this obj
return value
class post_property_set(object):
"""Method decorator that creates a field-backed read-write property that calls the
decorated method when set, with the old and new values"""
def __init__(m, post_func):
m.post_func = post_func
m.attr = "_" + post_func.__name__
def __get__(m, obj, t = None):
try:
if obj is None:
return m
else:
return getattr(obj, m.attr)
except AttributeError:
return None
def __set__(m, obj, value):
old_value = m.__get__(obj)
setattr(obj, m.attr, value)
m.post_func(obj, old_value, value)
class post_property_change(post_property_set):
"""Method decorator that creates a field-backed read-write property that calls the
decorated method when changed (going by == equality), with the old and new values"""
def __set__(m, obj, value):
old_value = m.__get__(obj)
changed = old_value != value
if changed:
setattr(obj, m.attr, value)
m.post_func(obj, old_value, value)
def staticclass(cls):
"""Class decorator that turns all methods into static methods, and properties into static properties"""
for name, value in getattrs(cls):
if callable(value):
setattr(cls, name, staticmethod(value))
elif isinstance(value, property):
setattr(cls, name, staticproperty(value.fget))
elif isinstance(value, lazy_property):
setattr(cls, name, lazy_staticproperty(value.func))
return cls
defaultdict = collections.defaultdict
deque = collections.deque
CounterDictionary = collections.Counter
WeakKeyDictionary = weakref.WeakKeyDictionary
WeakValueDictionary = weakref.WeakValueDictionary
class LazyDict(defaultdict):
"""Dict that populates entries lazily via a function that takes the key as the argument"""
def __init__(m, populate):
m.populate = populate
defaultdict.__init__(m)
def __missing__(m, key):
value = m.populate(key)
m[key] = value
return value
class OrderByKey:
"""Implements ordering and equality based on order_key()"""
# def order_key(m):
def order_type(m): return type(m)
def __eq__(m, other):
if isinstance(other, m.order_type()):
return m.order_key() == other.order_key()
else:
return NotImplemented
def __ne__(m, other):
if isinstance(other, m.order_type()):
return m.order_key() != other.order_key()
else:
return NotImplemented
def __lt__(m, other):
if isinstance(other, m.order_type()):
return m.order_key() < other.order_key()
else:
return NotImplemented
def __gt__(m, other):
if isinstance(other, m.order_type()):
return m.order_key() > other.order_key()
else:
return NotImplemented
def __le__(m, other):
if isinstance(other, m.order_type()):
return m.order_key() <= other.order_key()
else:
return NotImplemented
def __ge__(m, other):
if isinstance(other, m.order_type()):
return m.order_key() >= other.order_key()
else:
return NotImplemented
def u8(n):
return n & 0xff
def u16(n):
return n & 0xffff
def u32(n):
return n & 0xffffffff
def u64(n):
return n & 0xffffffffffffffff
def s8(n):
return (n & 0x7f) - (n & 0x80)
def s16(n):
return (n & 0x7fff) - (n & 0x8000)
def s32(n):
return (n & 0x7fffffff) - (n & 0x80000000)
def s64(n):
return (n & 0x7fffffffffffffff) - (n & 0x8000000000000000)
def f32(f):
raise Exception("not implemented yet")
def f64(f):
raise Exception("not implemented yet")
u8.min, u8.max = 0, 0xff
u16.min, u16.max = 0, 0xffff
u32.min, u32.max = 0, 0xffffffff
u64.min, u64.max = 0, 0xffffffffffffffff
s8.min, s8.max = -0x80, 0x7f
s16.min, s16.max = -0x8000, 0x7fff
s32.min, s32.max = -0x80000000, 0x7fffffff
s64.min, s64.max = -0x8000000000000000, 0x7fffffffffffffff
u8.struct_le = u8.struct_be = struct.Struct("=B")
s8.struct_le = s8.struct_le = struct.Struct("=b")
u16.struct_le, u16.struct_be = struct.Struct("<H"), struct.Struct(">H")
s16.struct_le, s16.struct_be = struct.Struct("<h"), struct.Struct(">h")
u32.struct_le, u32.struct_be = struct.Struct("<I"), struct.Struct(">I")
s32.struct_le, s32.struct_be = struct.Struct("<i"), struct.Struct(">i")
u64.struct_le, u64.struct_be = struct.Struct("<Q"), struct.Struct(">Q")
s64.struct_le, s64.struct_be = struct.Struct("<q"), struct.Struct(">q")
f32.struct_le, f32.struct_be = struct.Struct("<f"), struct.Struct(">f")
f64.struct_le, f64.struct_be = struct.Struct("<d"), struct.Struct(">d")
@context_manager("close")
class BinaryBase(object):
def close(m):
m.f.close()
def len(m):
old_pos = m.pos()
m.unwind()
len = m.pos()
m.setpos(old_pos)
return len
def truncate(m):
m.f.truncate()
def eof(m):
return m.f.tell() == m.len()
def pos(m):
return m.f.tell()
def setpos(m, val):
m.f.seek(val, 0)
def addpos(m, val):
m.f.seek(val, 1)
def setendpos(m, val):
m.f.seek(val, 2)
def subpos(m, val):
m.addpos(-val)
def swappos(m, val):
pos = m.pos()
m.setpos(val)
return pos
def rewind(m):
m.setpos(0)
def unwind(m):
m.f.seek(0, 2)
def flush(m):
m.f.flush()
@property
def length(m):
return m.len()
@property
def position(m):
return m.pos()
@position.setter
def position(m, value):
m.setpos(value)
class BinaryReader(BinaryBase):
"""Wraps a stream, allowing to easily read binary data from it"""
def __init__(m, path, big_end = False, enc = "utf-8", wenc = "utf-16"):
m.big_end, m.enc, m.wenc = big_end, enc, wenc
if isinstance(path, (str, CustomPath)):
m.f = file_open(path)
else:
m.f = path
def u8(m):
return u8.struct_le.unpack(m.f.read(1))[0]
def u16be(m):
return u16.struct_be.unpack(m.f.read(2))[0]
def u16le(m):
return u16.struct_le.unpack(m.f.read(2))[0]
def u16(m):
return m.u16be() if m.big_end else m.u16le()
def u32be(m):
return u32.struct_be.unpack(m.f.read(4))[0]
def u32le(m):
return u32.struct_le.unpack(m.f.read(4))[0]
def u32(m):
return m.u32be() if m.big_end else m.u32le()
def u64be(m):
return u64.struct_be.unpack(m.f.read(8))[0]
def u64le(m):
return u64.struct_le.unpack(m.f.read(8))[0]
def u64(m):
return m.u64be() if m.big_end else m.u64le()
def s8(m):
return s8.struct_le.unpack(m.f.read(1))[0]
def s16be(m):
return s16.struct_be.unpack(m.f.read(2))[0]
def s16le(m):
return s16.struct_le.unpack(m.f.read(2))[0]
def s16(m):
return m.s16be() if m.big_end else m.s16le()
def s32be(m):
return s32.struct_be.unpack(m.f.read(4))[0]
def s32le(m):
return s32.struct_le.unpack(m.f.read(4))[0]
def s32(m):
return m.s32be() if m.big_end else m.s32le()
def s64be(m):
return s64.struct_be.unpack(m.f.read(8))[0]
def s64le(m):
return s64.struct_le.unpack(m.f.read(8))[0]
def s64(m):
return m.s64be() if m.big_end else m.s64le()
def bytes(m, size, allow_eof=False):
result = m.f.read(size)
if len(result) != size and not allow_eof:
raise struct.error("end of file")
return result
def bytearray(m, size, allow_eof=False):
result = bytearray(size)
if m.f.readinto(result) != size and not allow_eof:
raise struct.error("end of file")
return result
def str(m, len, enc=None):
return m.bytes(len).decode(enc or m.enc)
def wstr(m, len, enc=None):
return m.bytes(len * 2).decode(enc or m.wenc)
def f32be(m):
return f32.struct_be.unpack(m.f.read(4))[0]
def f32le(m):
return f32.struct_le.unpack(m.f.read(4))[0]
def f32(m):
return m.f32be() if m.big_end else m.f32le()
def f64be(m):
return f64.struct_be.unpack(m.f.read(8))[0]
def f64le(m):
return f64.struct_le.unpack(m.f.read(8))[0]
def f64(m):
return m.f64be() if m.big_end else m.f64le()
def zbytes(m, size=None, count=1, allow_eof=False):
zero = b"\0" * count
if size is None:
# TODO: optimize if seeking supported?
result = b""
while True:
char = m.bytes(count, allow_eof)
if allow_eof and len(char) < count:
if char:
raise struct.error("end of file inside char")
break
elif char == zero:
break
else:
result += char
else:
result = m.bytes(size * count, allow_eof)
if allow_eof and count > 1 and len(result) % count:
raise struct.error("end of file inside char")
# TODO: any better way? (can't search/split if count > 1)
for i in range(0, size, count):
if result[i:i+count] == zero:
result = result[:i]
break
return result
def zstr(m, size=None, enc=None):
return m.zbytes(size).decode(enc or m.enc)
def wzstr(m, size=None, enc=None):
return m.zbytes(size, 2).decode(enc or m.wenc)
def struct(m, struct):
return struct.unpack(m.f.read(struct.size))
def list(m, func, size):
return [func() for _ in range(size)]
def bool(m):
return m.u8() != 0
def nat(m):
nat = 0