utils
General utilities, many used by shrinko. Sorry not sorry?
1"""General utilities, many used by shrinko. Sorry not sorry?""" 2 3import os, sys, io, bisect, random, copy, collections, itertools, struct, array, re, traceback, hashlib, math, string, weakref, operator, heapq, time, json, tempfile, shutil 4from datetime import datetime, timedelta, timezone 5from functools import reduce, total_ordering, lru_cache, cmp_to_key 6from copy import copy, deepcopy 7from io import BytesIO, StringIO 8from warnings import warn 9from reprlib import recursive_repr 10 11try: 12 import annotationlib 13 def get_meta_annotations(dict): 14 func = annotationlib.get_annotate_from_class_namespace(dict) 15 if not func: 16 return None 17 return annotationlib.call_annotate_function(func, annotationlib.Format.VALUE) 18except ImportError: 19 def get_meta_annotations(obj): 20 return obj.get("__annotations__", None) 21 22_my_excepthooks = [] 23def _my_excepthook(type, value, tb): 24 obj = traceback.TracebackException(type, value, tb) 25 for hook in _my_excepthooks: 26 hook(obj) 27 28 for line in obj.format(): 29 eprint(line, end="") 30 31def add_traceback_hook(hook): 32 """adds a hook to be called before printing a traceback, so that the hook can edit it freely""" 33 if not _my_excepthooks: 34 sys.excepthook = _my_excepthook 35 _my_excepthooks.append(hook) 36 37def eprint(*args, **kwargs): 38 """like print, but prints to stderr""" 39 print(*args, file=sys.stderr, **kwargs) 40 41def context_manager(method_name = "close"): 42 """Adds __enter__/__exit__ support for a class, using a specified method_name as the 'close' method""" 43 44 def decorator(cls): 45 method = getattr(cls, method_name) 46 47 def __enter__(m): 48 return m 49 def __exit__(m, t, v, s): 50 method(m) 51 52 cls.__enter__ = __enter__ 53 cls.__exit__ = __exit__ 54 return cls 55 return decorator 56 57def exec_def(name, code, namespace=None): 58 """execute 'code' and extract a definition named 'name' from it""" 59 if namespace is None: 60 namespace = {} 61 exec(code, namespace) 62 return namespace[name] 63 64def exec_script_by_path(path, name=None): 65 """executes script at 'path', returning its module object""" 66 import importlib.util 67 script_spec = importlib.util.spec_from_file_location(default(name, path_basename_no_extension(path)), path_absolute(path)) 68 script_mod = importlib.util.module_from_spec(script_spec) 69 script_spec.loader.exec_module(script_mod) 70 return script_mod 71 72def typename(obj): 73 """returns the name of the object's type""" 74 return type(obj).__name__ 75 76class Dynamic(object): 77 """An anonymous dynamic class with keyword-args-style initialization""" 78 79 def __init__(__m_, **__kw_): 80 __m_.__dict__ = __kw_ 81 82 @recursive_repr() 83 def __repr__(m): 84 contents = ", ".join(f"{k}={repr(v)}" for k, v in m.__dict__.items()) 85 return f"{typename(m)}({contents})" 86 87class DefaultDynamic(Dynamic): 88 """Like Dynamic, but accessing an unknown key gives None""" 89 90 def __getattr__(m, name): 91 return None 92 93def isdescriptor(obj): 94 """Return whether the value is a descriptor""" 95 return hasattr(obj, "__get__") or hasattr(obj, "__set__") or hasattr(obj, "__del__") 96 97class IncludeAttr: 98 """When defining an Enum/Tuple/etc, forces the attribute to be included, despite having a private name or being a function/descriptor/...""" 99 def __init__(m, value): 100 m.value = value 101 102class NoRenameAttr(IncludeAttr): 103 """When defining an Enum/Tuple/etc, forces the attribute to be included and not be renamed, despite having a name ending in _""" 104 def __init__(m, value): 105 m.value = value 106 107class ExcludeAttr: 108 """When defining an Enum/Tuple/etc, forces the attribute to be excluded, despite not having a private name nad not being a function/descriptor/...""" 109 def __init__(m, value): 110 m.value = value 111 112def _metaclass_collect_values(cls_dict, values, prefirst, next, with_aliases=True): 113 prev_value = prefirst 114 for key, value in default(values, cls_dict).items(): 115 keep_key = False 116 if key.startswith("__") and key.endswith("__"): 117 continue 118 elif isinstance(value, IncludeAttr): 119 keep_key = isinstance(value, NoRenameAttr) 120 value = value.value 121 elif key.startswith("_") or callable(value) or isdescriptor(value) or isinstance(value, ExcludeAttr): 122 continue 123 elif value is ...: 124 value = next(prev_value) 125 prev_value = value 126 127 yield key, value 128 if key.endswith("_") and not keep_key: 129 yield key[:-1], value # yield "proper" name last, so it overrides the '_' name in reverse maps 130 131def _metaclass_collect_fields(cls_dict, values): 132 fields = [] 133 defaults = [] 134 no_default = defaults # marker value, compare via 'is' 135 136 def next_no_default(_): 137 return no_default 138 139 for k, v in _metaclass_collect_values(cls_dict, values, None, next_no_default, with_aliases=False): 140 fields.append(k) 141 if v is not no_default: 142 defaults.append(v) 143 elif defaults: 144 raise Exception(f"Cannot specify required field {k} after optional fields") 145 146 return tuple(fields), tuple(defaults) 147 148class EnumMetaclass(type): 149 def __new__(meta, cls_name, cls_bases, cls_dict, _values=None): 150 if not cls_bases or Enum not in cls_bases: 151 return super().__new__(meta, cls_name, cls_bases, cls_dict) 152 153 # collect 154 enum_bases = tuple(base for base in cls_bases if base is not Enum and base.__class__ == EnumMetaclass) 155 156 first_auto = None if enum_bases else 0 157 def next_auto(prev): 158 if not isinstance(prev, (int, float)): 159 raise Exception(f"Cannot follow {prev} with ...") 160 return prev + 1 161 162 name_value_map = dict(_metaclass_collect_values(cls_dict, _values, first_auto, next_auto)) 163 164 full_name_value_map = name_value_map.copy() if enum_bases else name_value_map 165 for base in enum_bases: 166 full_name_value_map.update(base._values) 167 168 full_value_name_map = {v:k for k,v in full_name_value_map.items()} 169 170 # dict 171 def __init__(m, value): 172 if value in full_value_name_map: 173 m.value = value 174 elif value in full_name_value_map: 175 m.value = full_name_value_map[value] 176 else: 177 raise ValueError(f"{value} not value of {cls_name}") 178 179 def __eq__(m, other): 180 if m.__class__ != other.__class__: 181 return NotImplemented 182 return m.value == other.value 183 184 def __lt__(m, other): 185 if not isinstance(m, other.__class__) and not isinstance(other, m.__class__): 186 return NotImplemented 187 return m.value < other.value 188 189 def __str__(m): 190 return full_value_name_map[m.value] 191 192 def __repr__(m): 193 return f"{cls_name}.{full_value_name_map[m.value]}" 194 195 def __int__(m): 196 return m.value 197 198 def __bool__(m): 199 return m.value != 0 200 201 def __hash__(m): 202 return hash(m.value) 203 204 enum_dict = {} 205 enum_dict["__init__"] = __init__ 206 enum_dict["__eq__"] = __eq__ 207 enum_dict["__lt__"] = __lt__ 208 enum_dict["__str__"] = __str__ 209 enum_dict["__repr__"] = __repr__ 210 enum_dict["__int__"] = __int__ 211 enum_dict["__bool__"] = __bool__ 212 enum_dict["__hash__"] = __hash__ 213 enum_dict["__slots__"] = ("value",) 214 enum_dict["_values"] = full_name_value_map 215 216 for k, v in cls_dict.items(): 217 if isinstance(v, ExcludeAttr): 218 v = v.value 219 220 if k in name_value_map: 221 continue 222 elif k == "__slots__": 223 enum_dict[k] = enum_dict[k] + (v if isinstance(v, tuple) else (v,)) 224 elif k in enum_dict: 225 raise Exception(f"Cannot set {k} in Enum (but can override in inherited classes)") 226 else: 227 enum_dict[k] = v 228 229 enum_class = super().__new__(meta, cls_name, cls_bases, enum_dict) 230 231 for k, v in name_value_map.items(): 232 setattr(enum_class, k, enum_class(v)) 233 234 enum_class = total_ordering(enum_class) 235 return enum_class 236 237class Enum(metaclass=EnumMetaclass): 238 """If a class has Enum as a baseclass, it's transformed into an enum. 239 All non-private attributes of the class other than functions and descriptors become enum members. 240 Atributes with a value of ... receive values automatically. 241 Inherited classes behave like regular classes unless they have Enum as a direct baseclass. 242 Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter 243 Atributes with a name ending with _ can be referred to without the _. 244 """ 245 __slots__ = () 246 247class BitmaskMetaclass(type): 248 def __new__(meta, cls_name, cls_bases, cls_dict, _values=None): 249 if not cls_bases or Bitmask not in cls_bases: 250 return super().__new__(meta, cls_name, cls_bases, cls_dict) 251 252 # collect 253 bitmask_bases = tuple(base for base in cls_bases if base is not Bitmask and base.__class__ == BitmaskMetaclass) 254 255 first_auto = None if bitmask_bases else 0 256 def next_auto(prev): 257 if not isinstance(prev, int) or (prev != 0 and not is_pow2(prev)): 258 raise Exception(f"Cannot follow {prev} with ...") 259 return prev << 1 if prev != 0 else 1 260 261 name_mask_map = dict(_metaclass_collect_values(cls_dict, _values, first_auto, next_auto)) 262 263 full_name_mask_map = name_mask_map.copy() if bitmask_bases else name_mask_map 264 for base in bitmask_bases: 265 full_name_mask_map.update(base._fields) 266 267 full_mask_name_map = {v:k for k,v in full_name_mask_map.items()} 268 full_mask = reduce(lambda x,y:x|y, full_mask_name_map.keys(), 0) 269 270 # dict 271 def __init__(m, value = None, **kwargs): 272 if value is None: 273 m.value = 0 274 elif isinstance(value, int) and (value & full_mask) == value: 275 m.value = value 276 elif isinstance(value, str) and value in full_name_mask_map: 277 m.value = full_name_mask_map[value] 278 elif isinstance(value, m.__class__): 279 m.value = value.value 280 elif isinstance(value, (tuple, list)): 281 m.value = reduce(lambda x,y:x|y, (full_name_mask_map[part] for part in value), 0) 282 else: 283 raise ValueError(f"{value} not value of {cls_name}") 284 285 if kwargs: 286 for key, value in kwargs.items(): 287 setattr(m, key, value) 288 289 def __eq__(m, other): 290 if m.__class__ != other.__class__: 291 return NotImplemented 292 return m.value == other.value 293 294 def __hash__(m): 295 return hash(m.value) 296 297 def __str__(m): 298 if m.value: 299 values = [] 300 for mask, name in full_mask_name_map.items(): 301 if m.value & mask: 302 values.append(name) 303 304 return ",".join(values) 305 else: 306 return "" 307 308 def __repr__(m): 309 if m.value: 310 values = [] 311 for mask, name in full_mask_name_map.items(): 312 if m.value & mask: 313 values.append(f"{cls_name}.{name}") 314 315 return " | ".join(values) 316 else: 317 return f"{cls_name}(0)" 318 319 def __int__(m): 320 return m.value 321 322 def __bool__(m): 323 return m.value != 0 324 325 def __and__(m, other): 326 if m.__class__ != other.__class__: 327 return NotImplemented 328 return m.__class__(m.value & other.value) 329 330 def __or__(m, other): 331 if m.__class__ != other.__class__: 332 return NotImplemented 333 return m.__class__(m.value | other.value) 334 335 def __xor__(m, other): 336 if m.__class__ != other.__class__: 337 return NotImplemented 338 return m.__class__(m.value ^ other.value) 339 340 class no_bits_property: 341 def __init__(m, mask): 342 m.mask = mask 343 344 def __get__(m, obj, cls): 345 if obj is None: 346 return cls(m.mask) 347 else: 348 raise AttributeError() 349 350 def __set__(m, obj, value): 351 raise AttributeError() 352 353 class bit_property: 354 def __init__(m, mask): 355 m.mask = mask 356 357 def __get__(m, obj, cls): 358 if obj is None: 359 return cls(m.mask) 360 else: 361 return bool(obj.value & m.mask) 362 363 def __set__(m, obj, value): 364 if value: 365 obj.value |= m.mask 366 else: 367 obj.value &= ~m.mask 368 369 class bitfield_property: 370 def __init__(m, mask): 371 m.mask = mask 372 m.shift = count_trailing_zero_bits(mask) 373 374 def __get__(m, obj, cls): 375 if obj is None: 376 return cls(m.mask) 377 else: 378 return (obj.value & m.mask) >> m.shift 379 380 def __set__(m, obj, value): 381 obj.value = (obj.value & ~m.mask) | ((value << m.shift) & m.mask) 382 383 class typed_bitfield_property: 384 def __init__(m, mask, type): 385 m.mask, m.type = mask, type 386 m.shift = count_trailing_zero_bits(mask) 387 388 def __get__(m, obj, cls): 389 if obj is None: 390 return cls(m.mask) 391 else: 392 return m.type((obj.value & m.mask) >> m.shift) 393 394 def __set__(m, obj, value): 395 obj.value = (obj.value & ~m.mask) | ((int(value) << m.shift) & m.mask) 396 397 bitmask_dict = {} 398 bitmask_dict["__init__"] = __init__ 399 bitmask_dict["__eq__"] = __eq__ 400 bitmask_dict["__hash__"] = __hash__ 401 bitmask_dict["__str__"] = __str__ 402 bitmask_dict["__repr__"] = __repr__ 403 bitmask_dict["__int__"] = __int__ 404 bitmask_dict["__bool__"] = __bool__ 405 bitmask_dict["__and__"] = __and__ 406 bitmask_dict["__or__"] = __or__ 407 bitmask_dict["__xor__"] = __xor__ 408 bitmask_dict["__slots__"] = ("value",) 409 bitmask_dict["_fields"] = full_name_mask_map 410 411 annots = get_meta_annotations(cls_dict) 412 413 for name, mask in name_mask_map.items(): 414 if annots and name in annots: 415 bitmask_dict[name] = typed_bitfield_property(mask, annots[name]) 416 elif mask == 0: 417 bitmask_dict[name] = no_bits_property(mask) 418 elif is_pow2(mask): 419 bitmask_dict[name] = bit_property(mask) 420 else: 421 bitmask_dict[name] = bitfield_property(mask) 422 423 for k, v in cls_dict.items(): 424 if isinstance(v, ExcludeAttr): 425 v = v.value 426 427 if k in name_mask_map: 428 continue 429 elif k == "__slots__": 430 bitmask_dict[k] = bitmask_dict[k] + (v if isinstance(v, tuple) else (v,)) 431 elif k in bitmask_dict: 432 raise Exception(f"Cannot set {k} in Bitmask (but can override in inherited classes)") 433 else: 434 bitmask_dict[k] = v 435 436 return super().__new__(meta, cls_name, cls_bases, bitmask_dict) 437 438class Bitmask(metaclass=BitmaskMetaclass): 439 """If a class has Bitmask as a baseclass, it's transformed into a bitmask. 440 All non-private attributes of the class other than functions and descriptors become bitmask fields. 441 Atributes with a value of ... receive bits automatically. 442 A bitmask is like a struct, but with its fields mapped into a single bitmask integer. 443 Bitmasks can also be manipulated via: & | ^ 444 Inherited classes behave like regular classes unless they have Bitmask as a direct baseclass. 445 Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter 446 Atributes with a name ending with _ can be referred to without the _. 447 """ 448 __slots__ = () 449 450def _metaclass_collect_from_bases(fields, defaults, bases, is_new=False): 451 if not bases: 452 return fields, defaults 453 454 all_defaults = defaults 455 if len(defaults) == len(fields): 456 for base in reversed(bases): 457 newfunc = base.__new__ if is_new else base.__init__ 458 new_defaults = getattr(newfunc, "__defaults__", ()) 459 all_defaults = new_defaults + all_defaults 460 if len(new_defaults) != len(base._fields): 461 break 462 463 all_fields = sum((base._fields for base in bases), ()) + fields 464 return all_fields, all_defaults 465 466class TupleMetaclass(type): 467 def __new__(meta, cls_name, cls_bases, cls_dict, _values=None, **consts): 468 if not cls_bases or cls_bases == (tuple,) or Tuple not in cls_bases: 469 return super().__new__(meta, cls_name, cls_bases, cls_dict) 470 471 # collect 472 tuple_bases = tuple(base for base in cls_bases if base is not Tuple and base.__class__ == TupleMetaclass) 473 if len(tuple_bases) > 1: 474 raise Exception("Tuples cannot have multiple Tuple baseclasses") 475 476 fields, defaults = _metaclass_collect_fields(cls_dict, _values) 477 478 all_fields, all_defaults = _metaclass_collect_from_bases(fields, defaults, tuple_bases, is_new=True) 479 480 # dict 481 field_params_str = ', '.join(f for f in all_fields if f not in consts) 482 field_values_str = ', '.join(all_fields) + ("," if len(all_fields) == 1 else "") 483 new_def = f"def __new__(__cls, {field_params_str}):\n" 484 new_def += f" return tuple.__new__(__cls, ({field_values_str}))\n" 485 __new__ = exec_def("__new__", new_def, consts) 486 __new__.__defaults__ = all_defaults 487 488 def __reduce_ex__(m, proto): 489 return (m.__new__, (m.__class__, *m)) 490 491 @recursive_repr() 492 def __repr__(m): 493 contents = ", ".join(f"{f}={repr(getattr(m, f))}" for f in m._fields) 494 return f"{cls_name}({contents})" 495 496 def _replace(m, **changes): 497 return m.__class__(*map(changes.pop, m._fields, m)) 498 499 tuple_dict = {} 500 tuple_dict["__new__"] = __new__ 501 tuple_dict["__reduce_ex__"] = __reduce_ex__ 502 tuple_dict["__repr__"] = __repr__ 503 tuple_dict["__slots__"] = () # fields come from tuple 504 tuple_dict["_replace"] = _replace 505 tuple_dict["_fields"] = all_fields 506 507 start = len(all_fields) - len(fields) 508 for i, field in enumerate(fields): 509 tuple_dict[field] = property(operator.itemgetter(start + i)) 510 511 fields_set = set(fields) 512 513 for k, v in cls_dict.items(): 514 if isinstance(v, ExcludeAttr): 515 v = v.value 516 517 if k in fields_set: 518 continue 519 elif k == "__slots__": 520 tuple_dict[k] = tuple_dict[k] + (v if isinstance(v, tuple) else (v,)) 521 elif k in tuple_dict: 522 raise Exception(f"Cannot set {k} in Tuple (but can override in inherited classes)") 523 else: 524 tuple_dict[k] = v 525 526 return super().__new__(meta, cls_name, cls_bases, tuple_dict) 527 528class Tuple(tuple, metaclass=TupleMetaclass): 529 """If a class has Tuple as a baseclass, it's transformed into a named tuple. 530 All non-private attributes of the class other than functions and descriptors become tuple fields. 531 Atributes with a value of ... are required, otherwise - optional with the given default value. 532 The tuple behaves similarly to collections.namedtuple 533 Inherited classes behave like regular classes unless they have Tuple as a direct baseclass. 534 Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter, const base fields keyword parameters 535 Atributes with a name ending with _ can be referred to without the _. 536 """ 537 __slots__ = () 538 539class StructMetaclass(type): 540 def __new__(meta, cls_name, cls_bases, cls_dict, _values=None, **consts): 541 if not cls_bases or Struct not in cls_bases: 542 return super().__new__(meta, cls_name, cls_bases, cls_dict) 543 544 # collect 545 struct_bases = tuple(base for base in cls_bases if base is not Struct and base.__class__ == StructMetaclass) 546 if len(struct_bases) > 1: 547 raise Exception("Structs cannot have multiple Struct baseclasses") 548 549 fields, defaults = _metaclass_collect_fields(cls_dict, _values) 550 551 all_fields, all_defaults = _metaclass_collect_from_bases(fields, defaults, struct_bases) 552 553 # dict 554 init_def = f"def __init__(__m, {', '.join(f for f in all_fields if f not in consts)}):\n" 555 for field in all_fields: 556 init_def += f" __m.{field} = {field}\n" 557 if not all_fields: 558 init_def += " pass" 559 __init__ = exec_def("__init__", init_def, consts) 560 __init__.__defaults__ = all_defaults 561 562 @recursive_repr() 563 def __repr__(m): 564 contents = ", ".join(f"{f}={repr(getattr(m, f))}" for f in m._fields) 565 return f"{cls_name}({contents})" 566 567 # note - equality is by-identity (unless option to control is added?) 568 569 struct_dict = {} 570 struct_dict["__init__"] = __init__ 571 struct_dict["__repr__"] = __repr__ 572 struct_dict["__slots__"] = fields 573 struct_dict["_fields"] = all_fields 574 575 fields_set = set(fields) 576 577 for k, v in cls_dict.items(): 578 if isinstance(v, ExcludeAttr): 579 v = v.value 580 581 if k in fields_set: 582 continue 583 elif k == "__slots__": 584 struct_dict[k] = struct_dict[k] + (v if isinstance(v, tuple) else (v,)) 585 elif k in struct_dict: 586 raise Exception(f"Cannot set {k} in Struct (but can override in inherited classes)") 587 else: 588 struct_dict[k] = v 589 590 return super().__new__(meta, cls_name, cls_bases, struct_dict) 591 592class Struct(metaclass=StructMetaclass): 593 """If a class has Struct as a baseclass, it's transformed into a struct. 594 All non-private attributes of the class other than functions and descriptors become struct fields. 595 Atributes with a value of ... are required, otherwise - optional with the given default value. 596 A struct is like a mutable named tuple, except equality goes by identity. 597 Inherited classes behave like regular classes unless they have Struct as a direct baseclass. 598 Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter, const base fields keyword parameters 599 Atributes with a name ending with _ can be referred to without the _. 600 """ 601 __slots__ = () 602 603def SymbolClass(name): 604 """Create a class with the given name that returns cached symbols when invoked""" 605 class cls(object): 606 __slots__ = 'value' 607 cache = {} 608 609 def __new__(cls, value): 610 ident = cls.cache.get(value) 611 if ident is None: 612 ident = super().__new__(cls) 613 ident.value = value 614 cls.cache[value] = ident 615 return ident 616 617 def __str__(m): 618 return str(m.value) 619 def __bytes__(m): 620 return bytes(m.value) 621 def __repr__(m): 622 return f"`{m.value}" 623 624 cls.__name__ = name 625 return cls 626 627Symbol = SymbolClass("Symbol") 628 629class classproperty(object): 630 """Method decorator that turns it into a read-only class property""" 631 632 def __init__(m, func): 633 m.getter = func 634 635 def __get__(m, _, cls): 636 return m.getter(cls) 637 638 # must be read-only, sadly 639 640class staticproperty(object): 641 """Method decorator that turns it into a read-only static property""" 642 643 def __init__(m, func): 644 m.getter = func 645 646 def __get__(m, _, cls): 647 return m.getter() 648 649 # must be read-only, sadly 650 651class writeonly_property(object): 652 """Method decorator that turns it into a write-only property""" 653 654 def __init__(m, func): 655 m.func = func 656 657 def __set__(m, obj, value): 658 return m.func(obj, value) 659 660# reminder to self - if you want a "default property", aka one that has a default value but is settable, use a class field 661 662class lazy_property(object): 663 """Method decorator that turns it into a lazily-evaluated property""" 664 665 def __init__(m, func): 666 m.func = func 667 668 def __get__(m, obj, cls): 669 if obj is None: 670 return m 671 else: 672 value = m.func(obj) 673 obj.__dict__[m.func.__name__] = value # won't be called again for this obj 674 return value 675 676 @staticmethod 677 def is_set(obj, name): 678 return name in obj.__dict__ 679 680 @staticmethod 681 def clear(obj, name): 682 obj.__dict__.pop(name, None) 683 684class lazy_classproperty(object): 685 """Method decorator that turns it into a lazily-evaluated class property""" 686 687 def __init__(m, func): 688 m.func = func 689 690 def __get__(m, _, cls): 691 value = m.func(cls) 692 setattr(cls, m.func.__name__, value) # won't be called again for this obj 693 return value 694 695class lazy_staticproperty(object): 696 """Method decorator that turns it into a lazily-evaluated static property""" 697 698 def __init__(m, func): 699 m.func = func 700 701 def __get__(m, _, cls): 702 value = m.func() 703 setattr(cls, m.func.__name__, value) # won't be called again for this obj 704 return value 705 706class post_property_set(object): 707 """Method decorator that creates a field-backed read-write property that calls the 708 decorated method when set, with the old and new values""" 709 710 def __init__(m, post_func): 711 m.post_func = post_func 712 m.attr = "_" + post_func.__name__ 713 714 def __get__(m, obj, t = None): 715 try: 716 if obj is None: 717 return m 718 else: 719 return getattr(obj, m.attr) 720 except AttributeError: 721 return None 722 723 def __set__(m, obj, value): 724 old_value = m.__get__(obj) 725 setattr(obj, m.attr, value) 726 m.post_func(obj, old_value, value) 727 728class post_property_change(post_property_set): 729 """Method decorator that creates a field-backed read-write property that calls the 730 decorated method when changed (going by == equality), with the old and new values""" 731 732 def __set__(m, obj, value): 733 old_value = m.__get__(obj) 734 changed = old_value != value 735 736 if changed: 737 setattr(obj, m.attr, value) 738 m.post_func(obj, old_value, value) 739 740def staticclass(cls): 741 """Class decorator that turns all methods into static methods, and properties into static properties""" 742 for name, value in getattrs(cls): 743 if callable(value): 744 setattr(cls, name, staticmethod(value)) 745 elif isinstance(value, property): 746 setattr(cls, name, staticproperty(value.fget)) 747 elif isinstance(value, lazy_property): 748 setattr(cls, name, lazy_staticproperty(value.func)) 749 return cls 750 751defaultdict = collections.defaultdict 752deque = collections.deque 753CounterDictionary = collections.Counter 754 755WeakKeyDictionary = weakref.WeakKeyDictionary 756WeakValueDictionary = weakref.WeakValueDictionary 757 758class LazyDict(defaultdict): 759 """Dict that populates entries lazily via a function that takes the key as the argument""" 760 761 def __init__(m, populate): 762 m.populate = populate 763 defaultdict.__init__(m) 764 765 def __missing__(m, key): 766 value = m.populate(key) 767 m[key] = value 768 return value 769 770class OrderByKey: 771 """Implements ordering and equality based on order_key()""" 772 # def order_key(m): 773 def order_type(m): return type(m) 774 775 def __eq__(m, other): 776 if isinstance(other, m.order_type()): 777 return m.order_key() == other.order_key() 778 else: 779 return NotImplemented 780 def __ne__(m, other): 781 if isinstance(other, m.order_type()): 782 return m.order_key() != other.order_key() 783 else: 784 return NotImplemented 785 def __lt__(m, other): 786 if isinstance(other, m.order_type()): 787 return m.order_key() < other.order_key() 788 else: 789 return NotImplemented 790 def __gt__(m, other): 791 if isinstance(other, m.order_type()): 792 return m.order_key() > other.order_key() 793 else: 794 return NotImplemented 795 def __le__(m, other): 796 if isinstance(other, m.order_type()): 797 return m.order_key() <= other.order_key() 798 else: 799 return NotImplemented 800 def __ge__(m, other): 801 if isinstance(other, m.order_type()): 802 return m.order_key() >= other.order_key() 803 else: 804 return NotImplemented 805 806def u8(n): 807 return n & 0xff 808def u16(n): 809 return n & 0xffff 810def u32(n): 811 return n & 0xffffffff 812def u64(n): 813 return n & 0xffffffffffffffff 814 815def s8(n): 816 return (n & 0x7f) - (n & 0x80) 817def s16(n): 818 return (n & 0x7fff) - (n & 0x8000) 819def s32(n): 820 return (n & 0x7fffffff) - (n & 0x80000000) 821def s64(n): 822 return (n & 0x7fffffffffffffff) - (n & 0x8000000000000000) 823 824def f32(f): 825 raise Exception("not implemented yet") 826def f64(f): 827 raise Exception("not implemented yet") 828 829u8.min, u8.max = 0, 0xff 830u16.min, u16.max = 0, 0xffff 831u32.min, u32.max = 0, 0xffffffff 832u64.min, u64.max = 0, 0xffffffffffffffff 833s8.min, s8.max = -0x80, 0x7f 834s16.min, s16.max = -0x8000, 0x7fff 835s32.min, s32.max = -0x80000000, 0x7fffffff 836s64.min, s64.max = -0x8000000000000000, 0x7fffffffffffffff 837 838u8.struct_le = u8.struct_be = struct.Struct("=B") 839s8.struct_le = s8.struct_be = struct.Struct("=b") 840u16.struct_le, u16.struct_be = struct.Struct("<H"), struct.Struct(">H") 841s16.struct_le, s16.struct_be = struct.Struct("<h"), struct.Struct(">h") 842u32.struct_le, u32.struct_be = struct.Struct("<I"), struct.Struct(">I") 843s32.struct_le, s32.struct_be = struct.Struct("<i"), struct.Struct(">i") 844u64.struct_le, u64.struct_be = struct.Struct("<Q"), struct.Struct(">Q") 845s64.struct_le, s64.struct_be = struct.Struct("<q"), struct.Struct(">q") 846f32.struct_le, f32.struct_be = struct.Struct("<f"), struct.Struct(">f") 847f64.struct_le, f64.struct_be = struct.Struct("<d"), struct.Struct(">d") 848 849@context_manager("close") 850class BinaryBase(object): 851 def close(m): 852 m.f.close() 853 854 def len(m): 855 old_pos = m.pos() 856 m.unwind() 857 len = m.pos() 858 m.setpos(old_pos) 859 return len 860 861 def truncate(m): 862 m.f.truncate() 863 864 def remaining(m): 865 return m.len() - m.f.tell() 866 def eof(m): 867 return m.f.tell() == m.len() 868 869 def pos(m): 870 return m.f.tell() 871 def setpos(m, val): 872 m.f.seek(val, 0) 873 def addpos(m, val): 874 m.f.seek(val, 1) 875 def setendpos(m, val): 876 m.f.seek(val, 2) 877 878 def subpos(m, val): 879 m.addpos(-val) 880 def swappos(m, val): 881 pos = m.pos() 882 m.setpos(val) 883 return pos 884 885 def rewind(m): 886 m.setpos(0) 887 return m 888 def unwind(m): 889 m.f.seek(0, 2) 890 return m 891 892 def flush(m): 893 m.f.flush() 894 895 @property 896 def length(m): 897 return m.len() 898 @property 899 def position(m): 900 return m.pos() 901 @position.setter 902 def position(m, value): 903 m.setpos(value) 904 905def _read_zbytes(read_bytes, size, count, allow_eof): 906 zero = b"\0" * count 907 if size is None: 908 # TODO: optimize if seeking supported? 909 result = b"" 910 while True: 911 char = read_bytes(count, allow_eof) 912 if len(char) < count: 913 if char: 914 raise struct.error("end of file inside char") 915 break 916 elif char == zero: 917 break 918 else: 919 result += char 920 else: 921 result = read_bytes(size * count, allow_eof) 922 if count > 1 and len(result) % count: 923 raise struct.error("end of file inside char") 924 offset = 0 925 while True: 926 zero_i = result.find(zero, offset) 927 if zero_i < 0: 928 break 929 elif zero_i % count == 0: 930 result = result[:zero_i] 931 break 932 else: 933 offset = zero_i + 1 934 return result 935 936def _write_zbytes(write_bytes, v, size, count): 937 assert not (count > 1 and len(v) % count) 938 zero = b"\0" * count 939 if size is None: 940 write_bytes(v) 941 write_bytes(zero) 942 else: 943 if len(v) > size * count: 944 raise struct.error("input too large for zbytes with fixed size") 945 write_bytes(v) 946 for i in range(size - len(v) // count): 947 write_bytes(zero) 948 949class BinaryReader(BinaryBase): 950 """Wraps a stream, allowing to easily read binary data from it""" 951 952 def __init__(m, path, big_end = False, enc = "utf-8", wenc = "utf-16"): 953 m.big_end, m.enc, m.wenc = big_end, enc, wenc 954 955 if isinstance(path, (str, CustomPath)): 956 m.f = file_open(path) 957 else: 958 m.f = path 959 960 def u8(m): 961 return u8.struct_le.unpack(m.f.read(1))[0] 962 def u16be(m): 963 return u16.struct_be.unpack(m.f.read(2))[0] 964 def u16le(m): 965 return u16.struct_le.unpack(m.f.read(2))[0] 966 def u16(m): 967 return m.u16be() if m.big_end else m.u16le() 968 def u32be(m): 969 return u32.struct_be.unpack(m.f.read(4))[0] 970 def u32le(m): 971 return u32.struct_le.unpack(m.f.read(4))[0] 972 def u32(m): 973 return m.u32be() if m.big_end else m.u32le() 974 def u64be(m): 975 return u64.struct_be.unpack(m.f.read(8))[0] 976 def u64le(m): 977 return u64.struct_le.unpack(m.f.read(8))[0] 978 def u64(m): 979 return m.u64be() if m.big_end else m.u64le() 980 981 def s8(m): 982 return s8.struct_le.unpack(m.f.read(1))[0] 983 def s16be(m): 984 return s16.struct_be.unpack(m.f.read(2))[0] 985 def s16le(m): 986 return s16.struct_le.unpack(m.f.read(2))[0] 987 def s16(m): 988 return m.s16be() if m.big_end else m.s16le() 989 def s32be(m): 990 return s32.struct_be.unpack(m.f.read(4))[0] 991 def s32le(m): 992 return s32.struct_le.unpack(m.f.read(4))[0] 993 def s32(m): 994 return m.s32be() if m.big_end else m.s32le() 995 def s64be(m): 996 return s64.struct_be.unpack(m.f.read(8))[0] 997 def s64le(m): 998 return s64.struct_le.unpack(m.f.read(8))[0] 999 def s64(m): 1000 return m.s64be() if m.big_end else m.s64le() 1001 1002 def bytes(m, size, allow_eof=False): 1003 result = m.f.read(size) 1004 if len(result) != size and not allow_eof: 1005 raise struct.error("end of file") 1006 return result 1007 def bytearray(m, size, allow_eof=False): 1008 result = bytearray(size) 1009 if m.f.readinto(result) != size and not allow_eof: 1010 raise struct.error("end of file") 1011 return result 1012 1013 def str(m, len, enc=None): 1014 return m.bytes(len).decode(enc or m.enc) 1015 def wstr(m, len, enc=None): 1016 return m.bytes(len * 2).decode(enc or m.wenc) 1017 1018 def f32be(m): 1019 return f32.struct_be.unpack(m.f.read(4))[0] 1020 def f32le(m): 1021 return f32.struct_le.unpack(m.f.read(4))[0] 1022 def f32(m): 1023 return m.f32be() if m.big_end else m.f32le() 1024 def f64be(m): 1025 return f64.struct_be.unpack(m.f.read(8))[0] 1026 def f64le(m): 1027 return f64.struct_le.unpack(m.f.read(8))[0] 1028 def f64(m): 1029 return m.f64be() if m.big_end else m.f64le() 1030 1031 def zbytes(m, size=None, count=1, allow_eof=False): 1032 return _read_zbytes(m.bytes, size, count, allow_eof) 1033 1034 def zstr(m, size=None, enc=None): 1035 return m.zbytes(size).decode(enc or m.enc) 1036 def wzstr(m, size=None, enc=None): 1037 return m.zbytes(size, 2).decode(enc or m.wenc) 1038 1039 def struct(m, struct): 1040 return struct.unpack(m.f.read(struct.size)) 1041 1042 def list(m, func, size): 1043 return [func() for _ in range(size)] 1044 1045 def bool(m): 1046 return m.u8() != 0 1047 1048 def nat(m): 1049 nat = 0 1050 shift = 0 1051 more = True 1052 while more: 1053 val = m.u8() 1054 nat |= (val & 0x7f) << shift 1055 more = (val >> 7) 1056 shift += 7 1057 return nat 1058 1059 def int(m): 1060 nat = m.nat() 1061 if nat & 1: 1062 return -(nat - 1) >> 1 1063 else: 1064 return nat >> 1 1065 1066 def float(m): 1067 return m.f64() # python's float 1068 1069 def nbytes(m): 1070 return m.bytes(m.nat()) 1071 1072 def align(m, size, start = 0): 1073 misalign = (m.pos() - start) % size 1074 if misalign: 1075 m.addpos(size - misalign) 1076 1077class BinaryBitReader(BinaryBase): 1078 """Wraps a stream, allowing to easily read bits from it""" 1079 1080 def __init__(m, f, big_end = False): 1081 m.f = f 1082 m._bits = 0 1083 m._nbits = 0 1084 m.big_end = big_end 1085 1086 @property 1087 def bit_position(m): 1088 return m.pos() * 8 - m._nbits 1089 1090 def byte_align(m): # effectively flushes 1091 m.subpos(m._nbits // 8) 1092 m._bits, m._nbits = 0, 0 1093 1094 def _add_bits_le(m, strict): 1095 value = m.f.read(1) 1096 if value: 1097 m._bits |= ord(value) << m._nbits 1098 m._nbits += 8 1099 elif strict: 1100 raise struct.error("end of file") 1101 1102 def _bits_le(m, n, advance=True): 1103 while m._nbits < n: 1104 m._add_bits_le(advance) 1105 1106 value = m._bits & ((1 << n) - 1) 1107 if advance: 1108 m._bits >>= n 1109 m._nbits -= n 1110 return value 1111 1112 def _add_bits_be(m, strict): 1113 value = m.f.read(1) 1114 if value: 1115 m._bits = (m._bits << 8) | ord(value) 1116 m._nbits += 8 1117 elif strict: 1118 raise struct.error("end of file") 1119 1120 def _bits_be(m, n, advance=True): 1121 while m._nbits < n: 1122 m._add_bits_be(advance) 1123 1124 bottom_bits = m._nbits - n 1125 value = m._bits >> bottom_bits 1126 if advance: 1127 m._bits &= (1 << bottom_bits) - 1 1128 m._nbits -= n 1129 return value 1130 1131 def bits(m, n): 1132 return m._bits_be(n) if m.big_end else m._bits_le(n) 1133 1134 def bit(m): 1135 return m.bits(1) != 0 1136 1137 def peek_bits(m, n): 1138 return m._bits_be(n, False) if m.big_end else m._bits_le(n, False) 1139 1140 def peek_bit(m): 1141 return m.peek_bits(1) != 0 1142 1143 def _advance_bits_long(m, n): 1144 n -= m._nbits 1145 m._bits, m._nbits = 0, 0 1146 m.addpos(n // 8) 1147 n %= 8 1148 if n: 1149 m._add_bits_le(True) # le/be doesn't matter after above flush 1150 return n # bits left to advance 1151 1152 def _advance_bits_le(m, n): 1153 if n > m._nbits: 1154 n = m._advance_bits_long(n) 1155 m._bits >>= n 1156 m._nbits -= n 1157 1158 def _advance_bits_be(m, n): 1159 if n > m._nbits: 1160 n = m._advance_bits_long(n) 1161 m._bits &= (1 << (m._nbits - n)) - 1 1162 m._nbits -= n 1163 1164 def advance_bits(m, n): 1165 return m._advance_bits_be(n) if m.big_end else m._advance_bits_le(n) 1166 1167class BinaryWriter(BinaryBase): 1168 """Wraps a stream, allowing to easily write binary data to it""" 1169 1170 def __init__(m, path = None, big_end = False, enc = "utf-8", wenc = "utf-16"): 1171 m.big_end, m.enc, m.wenc = big_end, enc, wenc 1172 1173 if path is None: 1174 m.f = BytesIO() 1175 elif isinstance(path, (str, CustomPath)): 1176 m.f = file_create(path) 1177 else: 1178 m.f = path 1179 1180 def u8(m, v): 1181 m.f.write(u8.struct_le.pack(v)) 1182 def u16(m, v): 1183 if m.big_end: 1184 m.f.write(u16.struct_be.pack(v)) 1185 else: 1186 m.f.write(u16.struct_le.pack(v)) 1187 def u32(m, v): 1188 if m.big_end: 1189 m.f.write(u32.struct_be.pack(v)) 1190 else: 1191 m.f.write(u32.struct_le.pack(v)) 1192 def u64(m, v): 1193 if m.big_end: 1194 m.f.write(u64.struct_be.pack(v)) 1195 else: 1196 m.f.write(u64.struct_le.pack(v)) 1197 1198 def s8(m, v): 1199 m.f.write(s8.struct_le.pack(v)) 1200 def s16(m, v): 1201 if m.big_end: 1202 m.f.write(s16.struct_be.pack(v)) 1203 else: 1204 m.f.write(s16.struct_le.pack(v)) 1205 def s32(m, v): 1206 if m.big_end: 1207 m.f.write(s32.struct_be.pack(v)) 1208 else: 1209 m.f.write(s32.struct_le.pack(v)) 1210 def s64(m, v): 1211 if m.big_end: 1212 m.f.write(s64.struct_be.pack(v)) 1213 else: 1214 m.f.write(s64.struct_le.pack(v)) 1215 1216 def f32(m, v): 1217 if m.big_end: 1218 m.f.write(f32.struct_be.pack(v)) 1219 else: 1220 m.f.write(f32.struct_le.pack(v)) 1221 def f64(m, v): 1222 if m.big_end: 1223 m.f.write(f64.struct_be.pack(v)) 1224 else: 1225 m.f.write(f64.struct_le.pack(v)) 1226 1227 def bytes(m, v): 1228 m.f.write(v) 1229 1230 def str(m, v, enc=None): 1231 m.bytes(v.encode(enc or m.enc)) 1232 def wstr(m, v, enc=None): 1233 m.bytes(v.encode(enc or m.wenc)) 1234 1235 def zbytes(m, v, size=None, count=1): 1236 _write_zbytes(m.bytes, v, size, count) 1237 1238 def zstr(m, v, size=None, enc=None): 1239 m.zbytes(v.encode(enc or m.enc), size) 1240 def wzstr(m, v, size=None, enc=None): 1241 m.zbytes(v.encode(enc or m.wenc), size, 2) 1242 1243 def struct(m, struct, value): 1244 m.f.write(struct.pack(*value)) 1245 1246 def list(m, func, value): 1247 for v in value: 1248 func(v) 1249 1250 def fill(m, v, size): 1251 for i in range(size): 1252 m.u8(v) 1253 1254 def nat(m, v): 1255 assert v >= 0 1256 more = True 1257 while more: 1258 part = v & 0x7f 1259 v >>= 7 1260 more = v != 0 1261 m.u8(part | (more << 7)) 1262 1263 def bool(m, v): 1264 m.u8(1 if v else 0) 1265 1266 def int(m, v): 1267 if v >= 0: 1268 m.nat(v << 1) 1269 else: 1270 m.nat((-v << 1) + 1) 1271 1272 def float(m, v): 1273 m.f64(v) # python's float 1274 1275 def nbytes(m, v): 1276 m.nat(len(v)) 1277 m.bytes(v) 1278 1279 def align(m, size, start = 0, value = 0): 1280 misalign = (m.pos() - start) % size 1281 if misalign: 1282 for _ in range(size - misalign): 1283 m.u8(value) 1284 1285class BinaryBitWriter(BinaryBase): 1286 """Wraps a stream, allowing to easily write bits to it""" 1287 1288 def __init__(m, f, big_end = False): 1289 m.f = f 1290 m._bits = 0 1291 m._nbits = 0 1292 m.big_end = big_end 1293 1294 @property 1295 def bit_position(m): 1296 return m.pos() * 8 - m._nbits 1297 1298 def byte_align(m): 1299 m.flush() 1300 1301 def _remove_bits_le(m): 1302 m.f.write(byte(m._bits & 0xff)) 1303 m._bits >>= 8 1304 m._nbits -= 8 1305 1306 def _bits_le(m, n, v): 1307 m._bits |= v << m._nbits 1308 m._nbits += n 1309 1310 while m._nbits >= 8: 1311 m._remove_bits_le() 1312 1313 def _remove_bits_be(m): 1314 m._nbits -= 8 1315 m.f.write(byte(m._bits >> m._nbits)) 1316 m._bits &= (1 << m._nbits) - 1 1317 1318 def _bits_be(m, n, v): 1319 m._bits = (m._bits << n) | v 1320 m._nbits += n 1321 1322 while m._nbits >= 8: 1323 m._remove_bits_be() 1324 1325 def bits(m, n, v): 1326 if m.big_end: 1327 m._bits_be(n, v) 1328 else: 1329 m._bits_le(n, v) 1330 1331 def bit(m, v): 1332 m.bits(1, v) 1333 1334 def close(m): 1335 m.flush() 1336 super().close() 1337 1338 def _flush_le(m): 1339 if m._nbits: 1340 m.f.write(byte(m._bits & 0xff)) 1341 m._bits, m._nbits = 0, 0 1342 1343 def _flush_be(m): 1344 if m._nbits: 1345 m.f.write(byte(m._bits << (8 - m._nbits))) 1346 m._bits, m._nbits = 0, 0 1347 1348 def flush(m): 1349 if m.big_end: 1350 m._flush_be() 1351 else: 1352 m._flush_le() 1353 1354class BinaryBuffer: 1355 """Wraps a bytearray, allowing to easily read & write binary data in it""" 1356 # TODO: make more consistent with BinaryReader/Writer (big_end, enc, wenc) 1357 1358 def __init__(m, src): 1359 if isinstance(src, bytearray): 1360 m.buf = src 1361 else: 1362 m.buf = bytearray(src) 1363 1364 def __len__(m): 1365 return len(m.buf) 1366 1367 def r_u8(m, addr): 1368 return m.buf[addr] 1369 def w_u8(m, addr, val): 1370 m.buf[addr] = val 1371 1372 def r_u16(m, addr): 1373 return u16.struct_le.unpack_from(m.buf, addr)[0] 1374 def w_u16(m, addr, val): 1375 u16.struct_le.pack_into(m.buf, addr, val) 1376 1377 def r_u32(m, addr): 1378 return u32.struct_le.unpack_from(m.buf, addr)[0] 1379 def w_u32(m, addr, val): 1380 u32.struct_le.pack_into(m.buf, addr, val) 1381 1382 def r_u64(m, addr): 1383 return u64.struct_le.unpack_from(m.buf, addr)[0] 1384 def w_u64(m, addr, val): 1385 u64.struct_le.pack_into(m.buf, addr, val) 1386 1387 def r_s8(m, addr): 1388 return s8.struct_le.unpack_from(m.buf, addr)[0] 1389 def w_s8(m, addr, val): 1390 s8.struct_le.pack_into(m.buf, addr, val) 1391 1392 def r_s16(m, addr): 1393 return s16.struct_le.unpack_from(m.buf, addr)[0] 1394 def w_s16(m, addr, val): 1395 s16.struct_le.pack_into(m.buf, addr, val) 1396 1397 def r_s32(m, addr): 1398 return s32.struct_le.unpack_from(m.buf, addr)[0] 1399 def w_s32(m, addr, val): 1400 s32.struct_le.pack_into(m.buf, addr, val) 1401 1402 def r_s64(m, addr): 1403 return s64.struct_le.unpack_from(m.buf, addr)[0] 1404 def w_s64(m, addr, val): 1405 s64.struct_le.pack_into(m.buf, addr, val) 1406 1407 def r_f32(m, addr): 1408 return f32.struct_le.unpack_from(m.buf, addr)[0] 1409 def w_f32(m, addr, val): 1410 f32.struct_le.pack_into(m.buf, addr, val) 1411 1412 def r_f64(m, addr): 1413 return f64.struct_le.unpack_from(m.buf, addr)[0] 1414 def w_f64(m, addr, val): 1415 f64.struct_le.pack_into(m.buf, addr, val) 1416 1417 def r_bytes(m, addr, count, allow_eof=False): 1418 data = m.buf[addr:addr+count] 1419 if not allow_eof and len(data) < count: 1420 raise struct.error("end of buffer") 1421 return data 1422 1423 def r_zbytes(m, addr, size=None, count = 1, allow_eof=False): 1424 def bytes(count, allow_eof): 1425 nonlocal addr 1426 value = m.r_bytes(addr, count, allow_eof) 1427 addr += len(value) 1428 return value 1429 1430 return _read_zbytes(bytes, size, count, allow_eof) 1431 1432 def r_zstr(m, addr, size=None, enc="utf-8"): 1433 return m.r_zbytes(addr, size).decode(enc) 1434 def r_wzstr(m, addr, size=None, enc="utf-16"): 1435 return m.r_zbytes(addr, size, 2).decode(enc) 1436 1437 def w_bytes(m, addr, val): 1438 m.buf[addr:addr+len(val)] = val 1439 1440 def w_zbytes(m, addr, val, size=None, count=1): 1441 def bytes(val): 1442 nonlocal addr 1443 m.w_bytes(addr, val) 1444 addr += len(val) 1445 1446 _write_zbytes(bytes, val, size, count) 1447 1448 def w_zstr(m, addr, val, size=None, enc="utf-8"): 1449 m.w_zbytes(addr, val.encode(enc), size) 1450 def w_wzstr(m, addr, val, size=None, enc='utf-16'): 1451 m.w_zbytes(addr, val.encode(enc), size, 2) 1452 1453 def r_struct(m, addr, struct): 1454 return struct.unpack_from(m.buf, addr) 1455 def w_struct(m, addr, struct, val): 1456 struct.pack_into(m.buf, addr, *val) 1457 1458 def w_from(m, addr, src, src_addr, count): 1459 m.buf[addr:addr+count] = src.r_bytes(src_addr, count) 1460 def w_fill(m, addr, value, count): 1461 m.buf[addr:addr+count] = byte(value) * count 1462 def w_zero(m, addr, count): 1463 m.w_fill(addr, 0, count) 1464 1465def e(value): 1466 """Return if 'value' is not None (for my sanity and others' insanity)""" 1467 return value is not None 1468 1469def default(value, defval): 1470 """Return 'defval' if 'value' is None""" 1471 return value if value != None else defval 1472 1473def nop(value): 1474 """The identity function""" 1475 return value 1476 1477def product(items): 1478 """Return the product of 'items'""" 1479 result = 1 1480 for item in items: 1481 result *= item 1482 return result 1483 1484def str_insert(str, at, what): 1485 """Return a string based on 'str' with 'what' inserted at position 'at'""" 1486 return str[:at] + what + str[at:] 1487 1488def str_replace_at(str, at, count, what): 1489 """Return a string based on 'str' with 'what' replacing 'count' chars at position 'at'""" 1490 return str[:at] + what + str[at + count:] 1491 1492def str_replace_between(str, start, end, what): 1493 """Return a string based on 'str' with 'what' replacing chars between 'start' and 'end'""" 1494 return str[:start] + what + str[end:] 1495 1496def str_remove_at(str, at, count): 1497 """Return a string based on 'str' with 'count' chars removed at position 'at'""" 1498 return str[:at] + str[at + count:] 1499 1500def str_remove_between(str, start, end): 1501 """Return a string based on 'str' with chars removed between 'start' and 'end""" 1502 return str[:start] + str[end:] 1503 1504def str_trunc(str, count): 1505 """Truncates a string if larger than 'count' characters""" 1506 if len(str) > count: 1507 return str[:count] 1508 else: 1509 return str 1510 1511def str_ljust_trunc(str, count, fillchar = ' '): 1512 """Left-justifies a string and truncates it""" 1513 return str_trunc(str, count).ljust(count, fillchar) 1514 1515def str_rjust_trunc(str, count, fillchar = ' '): 1516 """Right-justifies a string and truncates it""" 1517 return str_trunc(str, count).rjust(count, fillchar) 1518 1519def str_remove_prefix(str, prefix): 1520 """Return a string based on 'str' with 'prefix' removed from its beginning""" 1521 if str.startswith(prefix): 1522 return str[len(prefix):] 1523 else: 1524 return str 1525 1526def str_remove_suffix(str, suffix): 1527 """Return a string based on 'str' with 'suffix' removed from its end""" 1528 if str.endswith(suffix): 1529 return str[:-len(suffix)] 1530 else: 1531 return str 1532 1533def str_before_first(str, match, s=None, e=None): 1534 """Return 'str' before the first 'match'""" 1535 i = str.find(match, s, e) 1536 return str[s:i] if i >= 0 else str[s:e] 1537 1538def str_before_last(str, match, s=None, e=None): 1539 """Return 'str' before the last 'match'""" 1540 i = str.rfind(match, s, e) 1541 return str[s:i] if i >= 0 else "" 1542 1543def str_after_first(str, match, s=None, e=None): 1544 """Return 'str' after the first 'match'""" 1545 i = str.find(match, s, e) 1546 return str[i+len(match):e] if i >= 0 else "" 1547 1548def str_after_last(str, match, s=None, e=None): 1549 """Return 'str' after the last 'match'""" 1550 i = str.rfind(match, s, e) 1551 return str[i+len(match):e] if i >= 0 else str[s:e] 1552 1553def str_split_first(str, match, s=None, e=None): 1554 """Return 'str' before and after the first 'match'""" 1555 i = str.find(match, s, e) 1556 return (str[s:i], str[i+len(match):e]) if i >= 0 else (str[s:e], "") 1557 1558def str_split_last(str, match, s=None, e=None): 1559 """Return 'str' before and after the last 'match'""" 1560 i = str.rfind(match, s, e) 1561 return (str[s:i], str[i+len(match):e]) if i >= 0 else ("", str[s:e]) 1562 1563def str_replace_batch(val, batch): 1564 """Return a string based on 'val' that contains replacements defined in 'batch'. 1565 'batch' is a dict or list of pairs, with each pair being: 1566 (str, str or (lambda: str)) - simple replacement 1567 (regex, str) - regex replacement (with regex pre-compilation) 1568 ((re, str), str) - regex replacement without pre-compilation""" 1569 if isinstance(batch, dict): 1570 batch = batch.items() 1571 1572 for k, v in batch: 1573 if isinstance(k, str): 1574 if callable(v): 1575 if k not in val: 1576 continue 1577 v = v() 1578 val = val.replace(k, v) 1579 elif isinstance(k, re.Pattern): 1580 val = k.sub(v, val) 1581 else: 1582 assert k[0] == re 1583 val = re.sub(k[1], v, val) 1584 return val 1585 1586str_replace_by_dict = str_replace_batch # compat. 1587 1588def list_chunk(list, size): 1589 """Split a list into sublists of size 'size' each (except possibly the last sublist)""" 1590 count = div_up(len(list), size) 1591 return [list[i * size : (i + 1) * size] for i in range(count)] 1592 1593def list_remove(list, func): 1594 """Remove elements from a list that match the given 'func'""" 1595 for i, item in enumerate(list): 1596 if func(item): 1597 del list[i] 1598 i -= 1 1599 1600def list_find(list, val): 1601 """Find the index of the given element in the list""" 1602 try: 1603 return list.index(val) 1604 except ValueError: 1605 return -1 1606 1607def list_find_where(list, func): 1608 """Find the index of the first element in a list that matches predicate 'func'""" 1609 for i, item in enumerate(list): 1610 if func(item): 1611 return i 1612 return -1 1613 1614def list_rfind_where(list, func): 1615 """Find the index of the last element in a list that matches predicate 'func'""" 1616 for i_rev, item in enumerate(reversed(list)): 1617 if func(item): 1618 return len(list) - 1 - i_rev 1619 return -1 1620 1621def list_get(list, i, defval = None): 1622 """Get the 'i'th element in the list, or 'defval' (default: None) if not a valid index""" 1623 return list[i] if 0 <= i < len(list) else defval 1624 1625def list_rget(list, i, defval = None): 1626 """Get the 'i'th element in the list from the end, or 'defval' (default: None) if not a valid index""" 1627 return list[-(i+1)] if 0 <= i < len(list) else defval 1628 1629def list_set(list, i, val, defval = None): 1630 """Set the 'i'th element in the list, growing the list with 'defval's (default: Nones) as needed""" 1631 assert i >= 0 1632 while i >= len(list): 1633 list.append(defval) 1634 list[i] = val 1635 1636str_get = list_get 1637str_rget = list_rget 1638str_chunk = list_chunk 1639 1640def list_pop(list, defval = None): 1641 """Pop the element from the list, or get 'defval' (default: None) if empty""" 1642 return list.pop() if list else defval 1643 1644def list_unpack(list, n, defval = None): 1645 """Return the 'n' first elements in the list, padding with 'defval' if needed""" 1646 for i in range(n): 1647 yield list_get(list, i, defval) 1648 1649def tuple_insert(tuple, i, newval): 1650 """Return a new tuple based on 'tuple' with 'newval' inserted at index 'i'""" 1651 return tuple[:i] + (newval,) + tuple[i:] 1652 1653def tuple_replace_at(tuple, i, newval): 1654 """Return a new tuple based on 'tuple' with 'newval' replacing the element at index 'i'""" 1655 return tuple[:i] + (newval,) + tuple[i+1:] 1656 1657def tuple_remove_at(tuple, i, count=1): 1658 """Return a new tuple based on 'tuple' with 'count' elements removed at index 'i'""" 1659 return tuple[:i] + tuple[i+count:] 1660 1661def dict_first_key(dict): 1662 for key in dict: 1663 return key 1664 1665def iter_chunk(src, count): 1666 it = iter(src) 1667 while True: 1668 chunk = tuple(itertools.islice(it, count)) 1669 if not chunk: 1670 break 1671 yield chunk 1672 1673def func_union(func1, func2, return_early=None, return_combine=None): 1674 """Return a function that behaves like func1 followed by func2. Either of func1/func2 may be None. 1675 'return_early' can decide whether to return func1's result. 'return_combine' can combine func1's and func2's results""" 1676 if func1 is None: 1677 return func2 1678 elif func2 is None: 1679 return func1 1680 elif return_early: 1681 def union(*args, **kwargs): 1682 ret = func1(*args, **kwargs) 1683 if return_early(ret): 1684 return ret 1685 return func2(*args, **kwargs) 1686 return union 1687 else: 1688 def union(*args, **kwargs): 1689 ret1 = func1(*args, **kwargs) 1690 ret2 = func2(*args, **kwargs) 1691 if return_combine: 1692 return return_combine(ret1, ret2) 1693 return None 1694 return union 1695 1696def getattrs(obj, private = True, magic = False): 1697 """Get all attributes of 'obj' (By default, including _privates but excluding __magic__)""" 1698 for attr in dir(obj): 1699 if not private and attr.startswith("_"): 1700 continue 1701 if not magic and attr.startswith("__") and attr.endswith("__"): 1702 continue 1703 yield attr, getattr(obj, attr) 1704 1705class Point(Tuple): 1706 """An (x,y) tuple representing a 2d point and supporting arithmetic operations""" 1707 x = y = ... 1708 1709 def __add__(m, other): 1710 assert isinstance(other, Point) 1711 return Point(m.x + other.x, m.y + other.y) 1712 1713 def __sub__(m, other): 1714 assert isinstance(other, Point) 1715 return Point(m.x - other.x, m.y - other.y) 1716 1717 def __mul__(m, other): 1718 if isinstance(other, Point): 1719 return Point(m.x * other.x, m.y * other.y) 1720 else: 1721 return Point(m.x * other, m.y * other) 1722 1723 def __rmul__(m, other): 1724 return Point(other * m.x, other * m.y) 1725 1726 def __truediv__(m, other): 1727 if isinstance(other, Point): 1728 return Point(m.x / other.x, m.y / other.y) 1729 else: 1730 return Point(m.x / other, m.y / other) 1731 1732 def __rtruediv__(m, other): 1733 return Point(other / m.x, other / m.y) 1734 1735 __div__ = __truediv__ 1736 __rdiv__ = __rtruediv__ 1737 1738 def __floordiv__(m, other): 1739 if isinstance(other, Point): 1740 return Point(m.x // other.x, m.y // other.y) 1741 else: 1742 return Point(m.x // other, m.y // other) 1743 1744 def __rfloordiv__(m, other): 1745 return Point(other // m.x, other // m.y) 1746 1747 def __mod__(m, other): 1748 if isinstance(other, Point): 1749 return Point(m.x % other.x, m.y % other.y) 1750 else: 1751 return Point(m.x % other, m.y % other) 1752 1753 def __rmod__(m, other): 1754 return Point(other % m.x, other % m.y) 1755 1756 def __abs__(m): 1757 return Point(abs(m.x), abs(m.y)) 1758 1759 def __neg__(m): 1760 return Point(-m.x, -m.y) 1761 1762 def __bool__(m): 1763 return m.x or m.y 1764 1765 def __ge__(m, other): 1766 assert isinstance(other, Point) 1767 return m.x >= other.x and m.y >= other.y 1768 1769 def __gt__(m, other): 1770 assert isinstance(other, Point) 1771 return m.x > other.x and m.y > other.y 1772 1773 def __le__(m, other): 1774 assert isinstance(other, Point) 1775 return m.x <= other.x and m.y <= other.y 1776 1777 def __lt__(m, other): 1778 assert isinstance(other, Point) 1779 return m.x < other.x and m.y < other.y 1780 1781 def set_x(m, x): 1782 return Point(x, m.y) 1783 1784 def set_y(m, y): 1785 return Point(m.x, y) 1786 1787 def int(m): 1788 return Point(int(m.x), int(m.y)) 1789 1790 def float(m): 1791 return Point(float(m.x), float(m.y)) 1792 1793 @classmethod 1794 def repeat(cls, value): 1795 return cls(value, value) 1796 1797 @property 1798 def norm_squared(m): 1799 return m.x * m.x + m.y * m.y 1800 1801 @property 1802 def norm(m): 1803 return math.sqrt(m.norm_squared) 1804 1805 @staticmethod 1806 def distance_squared(m, o): 1807 return (m - o).norm_squared 1808 1809 @staticmethod 1810 def distance(m, o): 1811 return (m - o).norm 1812 1813Point.zero = Point(0, 0) 1814 1815class Rect(Tuple): 1816 """An (x,y,w,h) tuple representing a 2d rectangle""" 1817 x = y = w = h = ... 1818 1819 @property 1820 def x2(m): 1821 return m.x + m.w 1822 1823 @property 1824 def y2(m): 1825 return m.y + m.h 1826 1827 @property 1828 def pos(m): 1829 return Point(m.x, m.y) 1830 1831 @property 1832 def size(m): 1833 return Point(m.w, m.h) 1834 1835 @property 1836 def pos2(m): 1837 return Point(m.x2, m.y2) 1838 1839 @property 1840 def center(m): 1841 return m.pos + m.size / 2 1842 1843 def __bool__(m): 1844 return m.w > 0 and m.h > 0 1845 1846 def __contains__(m, p): 1847 if isinstance(p, Point): 1848 return p >= m.pos and p < m.pos2 1849 elif isinstance(p, Rect): 1850 return p.pos >= m.pos and p.pos2 <= m.pos2 1851 else: 1852 raise Exception("Not implemented") 1853 1854 def overlaps(m, p): 1855 assert isinstance(p, Rect) 1856 return p.pos < m.pos2 and p.pos2 > m.pos 1857 1858 def __and__(m, p): 1859 assert isinstance(p, Rect) 1860 return Rect.from_coords(max(m.x, p.x), max(m.y, p.y), max(min(m.x2, p.x2), 0), max(min(m.y2, p.y2), 0)) 1861 1862 def __add__(m, other): 1863 assert isinstance(other, Point) 1864 return Rect(m.x + other.x, m.y + other.y, m.w, m.h) 1865 1866 def __sub__(m, other): 1867 assert isinstance(other, Point) 1868 return Rect(m.x - other.x, m.y - other.y, m.w, m.h) 1869 1870 @classmethod 1871 def from_pos_size(cls, pos, size): 1872 return cls(pos.x, pos.y, size.x, size.y) 1873 1874 @classmethod 1875 def from_pos(cls, pos, pos2): 1876 return cls(pos.x, pos.y, pos2.x - pos.x, pos2.y - pos.y) 1877 1878 @classmethod 1879 def from_coords(cls, x, y, x2, y2): 1880 return cls(x, y, x2 - x, y2 - y) 1881 1882Rect.zero = Rect(0, 0, 0, 0) 1883 1884class ProjectedDictBase(dict): 1885 """A dict baseclass where keys are projected via _project before compared""" 1886 @classmethod 1887 def _project(cls, key): 1888 raise NotImplementedError() 1889 1890 def __init__(m, E=None, **F): 1891 super().__init__() 1892 m.update(E, **F) 1893 def __getitem__(m, key): 1894 return super().__getitem__(m.__class__._project(key)) 1895 def __setitem__(m, key, value): 1896 super().__setitem__(m.__class__._project(key), value) 1897 def __delitem__(m, key): 1898 return super().__delitem__(m.__class__._project(key)) 1899 def __contains__(m, key): 1900 return super().__contains__(m.__class__._project(key)) 1901 def pop(m, key, *args, **kwargs): 1902 return super().pop(m.__class__._project(key), *args, **kwargs) 1903 def get(m, key, *args, **kwargs): 1904 return super().get(m.__class__._project(key), *args, **kwargs) 1905 def setdefault(m, key, *args, **kwargs): 1906 return super().setdefault(m.__class__._project(key), *args, **kwargs) 1907 1908 def update(m, E=None, **F): 1909 if E: 1910 if hasattr(E, "items"): 1911 for k, v in E.items(): 1912 m[k] = v 1913 else: 1914 for k, v in E: 1915 m[k] = v 1916 1917 if F: 1918 for k, v in F.items(): 1919 m[k] = v 1920 1921class CaseInsensitiveDict(ProjectedDictBase): 1922 """A dict where key comparison is case-insensitive""" 1923 @classmethod 1924 def _project(cls, key): 1925 return key.lower() 1926 1927class defaultlist(list): 1928 """A list allowing read/write of arbitrary indices, filling unused indices via 'defgetter'()""" 1929 def __init__(m, defgetter): 1930 m.defgetter = defgetter 1931 1932 def _fill(m, i): 1933 if isinstance(i, slice): 1934 while i.stop > len(m): 1935 m.append(m.defgetter()) 1936 else: 1937 while i >= len(m): 1938 m.append(m.defgetter()) 1939 1940 def __getitem__(m, i): 1941 m._fill(i) 1942 return list.__getitem__(m, i) 1943 1944 def __setitem__(m, i, val): 1945 m._fill(i) 1946 list.__setitem__(m, i, val) 1947 1948class MultidimArray(object): 1949 """A multi-dimensional array of a fixed size""" 1950 def __init__(m, size, defval=None): 1951 m.dim = len(size) 1952 m.size = size 1953 m.array = [defval] * product(size) 1954 1955 def copy(m): 1956 return deepcopy(m) 1957 1958 def _getindex(m, indices): 1959 array_index = 0 1960 for i in range(m.dim): 1961 index, size = indices[i], m.size[i] 1962 if not (0 <= index < size): 1963 raise IndexError(indices) 1964 if i > 0: 1965 array_index *= size 1966 array_index += index 1967 return array_index 1968 1969 def __getitem__(m, indices): 1970 return m.array[m._getindex(indices)] 1971 1972 def __setitem__(m, indices, value): 1973 m.array[m._getindex(indices)] = value 1974 1975 def indices(m): 1976 indices = [0] * m.dim 1977 while True: 1978 yield indices 1979 1980 for i in reversed(range(m.dim)): 1981 indices[i] += 1 1982 if indices[i] >= m.size[i]: 1983 indices[i] = 0 1984 else: 1985 break 1986 else: 1987 break 1988 1989class HeapQueue: 1990 """A class wrapper over heapq""" 1991 def __init__(m, iterable=None): 1992 m.list = list(iterable) if e(iterable) else [] 1993 heapq.heapify(m.list) 1994 1995 def add(m, v): 1996 heapq.heappush(m.list, v) 1997 1998 def peekleft(m): 1999 return m.list[0] 2000 2001 def popleft(m): 2002 return heapq.heappop(m.list) 2003 2004 def __len__(m): 2005 return len(m.list) 2006 2007 def __repr__(m): 2008 return f"HeapQueue({repr(m.list)})" 2009 2010class RangeSet: 2011 """A set of non-empty non-overlapping/touching ranges (tuples of (start,stop))""" 2012 def __init__(m, ranges=None): 2013 m.list = [] 2014 for range in ranges or (): 2015 m.add(range) 2016 2017 def add(m, v): 2018 v_start, v_stop = v 2019 if v_start >= v_stop: 2020 return 2021 i_start = i_end = bisect.bisect_right(m.list, (v_start, math.inf)) 2022 2023 if i_start > 0: 2024 prev_start, prev_stop = m.list[i_start - 1] # prev_start <= v_start 2025 if prev_stop >= v_start: 2026 if prev_stop >= v_stop: 2027 return 2028 i_start -= 1 2029 v = (v_start := prev_start, v_stop) 2030 2031 while i_end < len(m.list): 2032 next_start, next_stop = m.list[i_end] # next_start > v_start 2033 if next_start > v_stop: 2034 break 2035 i_end += 1 2036 if next_stop > v_stop: 2037 v = (v_start, v_stop := next_stop) 2038 break 2039 2040 if not isinstance(v, tuple): 2041 v = (v_start, v_stop) 2042 m.list[i_start:i_end] = (v,) 2043 2044 def remove(m, v): 2045 v_start, v_stop = v 2046 if v_start >= v_stop: 2047 return 2048 i_start = i_end = bisect.bisect_left(m.list, (v_start, -math.inf)) 2049 repls = () 2050 2051 if i_start > 0: 2052 prev_start, prev_stop = m.list[i_start - 1] # prev_start < v_start 2053 if prev_stop > v_start: 2054 i_start -= 1 2055 repls = (*repls, (prev_start, v_start)) 2056 if prev_stop > v_stop: 2057 repls = (*repls, (v_stop, prev_stop)) 2058 2059 while i_end < len(m.list): 2060 next_start, next_stop = m.list[i_end] # next_start >= v_start 2061 if next_start >= v_stop: 2062 break 2063 i_end += 1 2064 if next_stop > v_stop: 2065 repls = (*repls, (v_stop, next_stop)) 2066 break 2067 2068 if i_end != i_start: 2069 m.list[i_start:i_end] = repls 2070 2071 def __iadd__(m, o): 2072 for v in o: 2073 m.add(v) 2074 __ior__ = __iadd__ 2075 def __isub__(m, o): 2076 for v in o: 2077 m.remove(v) 2078 2079 def __bool__(m): 2080 return bool(m.list) 2081 # __len__ - len or sum-lens? 2082 def __iter__(m): 2083 return iter(m.list) 2084 2085 def __repr__(m): 2086 return f"RangeSet({repr(m.list)})" 2087 2088class RawIOBaseWSeek(io.RawIOBase): 2089 """Like RawIOBase, but allows seeking""" 2090 def seek(m, position, whence=io.SEEK_SET): 2091 if whence == io.SEEK_SET: 2092 m.position = position 2093 elif whence == io.SEEK_CUR: 2094 m.position += position 2095 elif whence == io.SEEK_END: 2096 m.position = m.length + position 2097 return m.position 2098 2099class PartialIO(RawIOBaseWSeek): 2100 """Exposes a region of an existing stream as a stream""" 2101 def __init__(m, io, offset, length=None): 2102 length = length if e(length) else io.length - offset 2103 m.io = io 2104 m.position = 0 2105 m.offset = offset 2106 m.length = length 2107 2108 def flush(m): 2109 return m.io.flush() 2110 2111 def readinto(m, target): 2112 size = len(target) 2113 view = memoryview(target) 2114 2115 size = max(min(size, m.length - m.position), 0) 2116 m.io.seek(m.offset + m.position) 2117 count = m.io.readinto(view[:size]) 2118 2119 m.position += count 2120 return count 2121 2122 def write(m, data): 2123 size = len(data) 2124 view = memoryview(data) 2125 2126 size = max(min(size, m.length - m.position), 0) 2127 m.io.seek(m.offset + m.position) 2128 count = m.io.write(view[:size]) 2129 2130 m.position += count 2131 return count 2132 2133class SegmentedIO(RawIOBaseWSeek): 2134 """A stream that combines several existing streams""" 2135 class Segment(Tuple): 2136 start = file = offset = size = ... 2137 2138 def __init__(m): 2139 m.segments = [] 2140 m.last_segment = None 2141 m.position = 0 2142 m.length = 0 2143 2144 def add(m, file, offset, size): 2145 m.segments.append(m.Segment(m.length, file, offset, size)) 2146 m.length += size 2147 2148 def flush(m): 2149 for segment in m.segments: 2150 segment.file.flush() 2151 2152 def _find(m, offset): 2153 segment = m.last_segment 2154 if segment and segment.start <= offset < segment.start + segment.size: 2155 return segment, offset - segment.start 2156 2157 for segment in m.segments: 2158 if segment.start <= offset < segment.start + segment.size: 2159 m.last_segment = segment 2160 return segment, offset - segment.start 2161 2162 return None, 0 2163 2164 def readinto(m, target): 2165 offset = 0 2166 size = len(target) 2167 view = memoryview(target) 2168 2169 while offset < size: 2170 segment, offset_in_seg = m._find(m.position) 2171 if segment is None: 2172 break 2173 2174 segment.file.seek(segment.offset + offset_in_seg) 2175 seg_count = min(segment.size - offset_in_seg, size - offset) 2176 seg_count = segment.file.readinto(view[offset : offset + seg_count]) 2177 if seg_count is None: 2178 return offset if offset else None 2179 2180 if seg_count == 0: 2181 break 2182 2183 offset += seg_count 2184 m.position += seg_count 2185 2186 return offset 2187 2188 def write(m, data): 2189 offset = 0 2190 size = len(data) 2191 view = memoryview(data) 2192 2193 while offset < size: 2194 segment, offset_in_seg = m._find(m.position) 2195 if segment is None: 2196 break 2197 2198 segment.file.seek(segment.offset + offset_in_seg) 2199 seg_count = min(segment.size - offset_in_seg, size - offset) 2200 seg_count = segment.file.write(view[offset : offset + seg_count]) 2201 if seg_count is None: 2202 return offset if offset else None 2203 2204 if seg_count == 0: 2205 break 2206 2207 offset += seg_count 2208 m.position += seg_count 2209 2210 return offset 2211 2212class ByteArrayIO(RawIOBaseWSeek): 2213 """Exposes a bytearray as a stream""" # did I miss this in the stdlib? 2214 def __init__(m, arr): 2215 m.arr = arr 2216 m.position = 0 2217 2218 @property 2219 def length(m): 2220 return len(m.arr) 2221 2222 def readinto(m, target): 2223 pos = m.position 2224 slice = m.arr[pos:pos + len(target)] 2225 count = len(slice) 2226 target[:count] = slice 2227 m.position += count 2228 return count 2229 2230 def write(m, data): 2231 pos = m.position 2232 if pos > len(m.arr): # slice syntax doesn't handle this case... 2233 m.arr += bytearray(pos - len(m.arr)) 2234 size = len(data) 2235 m.arr[pos:pos + size] = data 2236 m.position += size 2237 return size 2238 2239class IOWrapper: 2240 def __init__(m, stream): 2241 m.stream = stream 2242 def __enter__(m): 2243 return m.stream 2244 def __exit__(m, *_): 2245 pass 2246 2247class CustomPath(str): 2248 """A path that refers to some custom-obtained data""" 2249 2250 def open(m): 2251 raise FileNotFoundError(type(m)) 2252 def open_text(m, encoding, errors, newline): 2253 raise FileNotFoundError(type(m)) 2254 def create(m): 2255 raise FileNotFoundError(type(m)) 2256 def create_text(m, encoding, errors, newline): 2257 raise FileNotFoundError(type(m)) 2258 2259def path_is_native(path): 2260 return not isinstance(path, CustomPath) 2261 2262class StdPath(CustomPath): 2263 """A path that refers to the standard streams""" 2264 2265 def open(m): 2266 return IOWrapper(sys.stdin.buffer) 2267 2268 def open_text(m, encoding, errors, newline): 2269 sys.stdin.reconfigure(encoding=encoding, errors=errors, newline=newline) 2270 return IOWrapper(sys.stdin) 2271 2272 def create(m): 2273 return IOWrapper(sys.stdout.buffer) 2274 2275 def create_text(m, encoding, errors, newline): 2276 sys.stdout.reconfigure(encoding=encoding, errors=errors, newline=newline) 2277 return IOWrapper(sys.stdout) 2278 2279 append = create 2280 append_text = create_text 2281 2282class DataPath(CustomPath): 2283 """A path that refers to some data""" 2284 2285 def __new__(cls, value, data): 2286 path = str.__new__(cls, value) 2287 path.data = data 2288 return path 2289 2290 def open(m): 2291 return BytesIO(m.data) 2292 2293 def open_text(m, encoding, errors, newline): 2294 return StringIO(m.data.decode(encoding, errors), newline=newline) 2295 2296class URLPath(CustomPath): 2297 """A path that's actually a URL""" 2298 2299 def open(m): 2300 from urllib.request import urlopen 2301 return urlopen(m) 2302 2303 def open_text(m, encoding, errors, newline): 2304 return io.TextIOWrapper(m.open(), encoding, errors, newline) 2305 2306def file_open(path): 2307 """Open a binary file for reading""" 2308 if isinstance(path, CustomPath): 2309 return path.open() 2310 else: 2311 return open(path, "rb") 2312 2313def file_open_text(path, encoding = "utf-8", errors = None, newline = None): 2314 """Open a text file for reading""" 2315 if isinstance(path, CustomPath): 2316 return path.open_text(encoding, errors, newline) 2317 else: 2318 return open(path, "r", encoding=encoding, errors=errors, newline=newline) 2319 2320def file_open_maybe_text(path, encoding = "utf-8", newline = "\n"): 2321 return file_open_text(path, encoding, "surrogateescape", newline) 2322 2323def file_create(path): 2324 """Create or replace a binary file for writing""" 2325 if isinstance(path, CustomPath): 2326 return path.create() 2327 else: 2328 return open(path, "wb") 2329 2330def file_create_text(path, encoding = "utf-8", errors = None, newline = "\n"): 2331 """Create or replace a text file for writing""" 2332 if isinstance(path, CustomPath): 2333 return path.create_text(encoding, errors, newline) 2334 else: 2335 return open(path, "w", encoding=encoding, errors=errors, newline=newline) 2336 2337def file_create_maybe_text(path, encoding = "utf-8", newline = "\n"): 2338 return file_create_text(path, encoding, "surrogateescape", newline) 2339 2340def file_prepare_append(path): 2341 """Open or create a binary file for appending""" 2342 if isinstance(path, CustomPath): 2343 return path.append() 2344 else: 2345 return open(path, "ab") 2346 2347def file_prepare_append_text(path, encoding = "utf-8", errors = None, newline = "\n"): 2348 """Open or create a text file for appending""" 2349 if isinstance(path, CustomPath): 2350 return path.append_text(encoding, errors, newline) 2351 else: 2352 return open(path, "a", encoding=encoding, errors=errors, newline=newline) 2353 2354def file_prepare_append_maybe_text(path, encoding = "utf-8", newline = "\n"): 2355 return file_prepare_append_text(path, encoding, "surrogateescape", newline) 2356 2357def file_read(path, offset = 0, size = None): 2358 """Read all data from a binary file (or optionally, a subset of data)""" 2359 with file_open(path) as f: 2360 if offset: 2361 f.seek(offset, 0) 2362 if size: 2363 return f.read(size) 2364 else: 2365 return f.read() 2366 2367def file_read_text(path, encoding = "utf-8", errors = None, newline = None): 2368 """Read all text from a text file""" 2369 with file_open_text(path, encoding, errors, newline) as f: 2370 return f.read() 2371 2372def file_read_maybe_text(path, encoding = "utf-8", newline = None): 2373 return file_read_text(path, encoding, "surrogateescape", newline) 2374 2375def file_read_json(path, **json_kwargs): 2376 """Read data from a json file""" 2377 with file_open_text(path) as f: 2378 return json.load(f, **json_kwargs) 2379 2380def file_write(path, value): 2381 """Create or replace a binary file, writing 'value' into it""" 2382 with file_create(path) as f: 2383 f.write(value) 2384 2385def file_write_text(path, value, encoding = "utf-8", errors = None, newline = "\n"): 2386 """Create or replace a text file, writing 'value' into it""" 2387 with file_create_text(path, encoding, errors, newline) as f: 2388 f.write(value) 2389 2390def file_write_maybe_text(path, value, encoding = "utf-8", newline = "\n"): 2391 file_write_text(path, value, encoding, "surrogateescape", newline) 2392 2393def file_write_json(path, value, **json_kwargs): 2394 """Create or replace a json file, writing 'data' into it""" 2395 with file_create_text(path) as f: 2396 json.dump(value, f, **json_kwargs) 2397 2398def file_append(path, value): 2399 """Open or create a binary file, appending 'value' into it""" 2400 with file_prepare_append(path) as f: 2401 f.write(value) 2402 2403def file_append_text(path, value, encoding = "utf-8", errors = None, newline = "\n"): 2404 """Open or create a text file, appending 'value' into it""" 2405 with file_prepare_append_text(path, encoding, errors, newline) as f: 2406 f.write(value) 2407 2408def file_append_maybe_text(path, value, encoding = "utf-8", newline = "\n"): 2409 file_append_text(path, value, encoding, "surrogateescape", newline) 2410 2411def try_file_read(path, defval = None): 2412 """Try reading all data from a binary file, or return 'defval' on any error""" 2413 try: 2414 return file_read(path) 2415 except Exception: 2416 return defval 2417 2418def try_file_read_text(path, defval = None, encoding = "utf-8", errors = None, newline = None): 2419 """Try reading all text from a text file, or return 'defval' on any error""" 2420 try: 2421 return file_read_text(path, encoding, errors, newline) 2422 except Exception: 2423 return defval 2424 2425def try_file_read_maybe_text(path, defval = None, encoding = "utf-8", newline = None): 2426 return try_file_read_text(path, defval, encoding, "surrogateescape", newline) 2427 2428def try_file_read_json(path, defval = None, **json_kwargs): 2429 """Try reading data from a json file, or return 'defval' on any error""" 2430 try: 2431 return file_read_json(path, **json_kwargs) 2432 except Exception: 2433 return defval 2434 2435def try_file_write(path, value): 2436 """Try creating or replacing a binary file, writing 'value' into it. Return if succeeded""" 2437 try: 2438 file_write(path, value) 2439 return True 2440 except Exception: 2441 return False 2442 2443def try_file_write_text(path, value, encoding = "utf-8", errors = None, newline = "\n"): 2444 """Try creating or replacing a text file, writing 'value' into it. Return if succeeded""" 2445 try: 2446 file_write_text(path, value, encoding, errors, newline) 2447 return True 2448 except Exception: 2449 return False 2450 2451def try_file_write_maybe_text(path, value, encoding = "utf-8", newline = None): 2452 return try_file_write_text(path, value, encoding, "surrogateescape", newline) 2453 2454def try_file_write_json(path, value, **json_kwargs): 2455 """Try creating or replacing a json file, writing 'value' into it. Return if succeeded""" 2456 try: 2457 file_write_json(path, value, **json_kwargs) 2458 return True 2459 except Exception: 2460 return False 2461 2462def file_delete(path): 2463 """Delete a file if it exists""" 2464 try: 2465 os.remove(path) 2466 return True 2467 except FileNotFoundError: 2468 return False 2469 2470file_delete_if_needed = file_delete # old name 2471 2472def file_temp(): 2473 """Create a temporary file (no auto-deletion)""" 2474 result = tempfile.NamedTemporaryFile(delete=False) 2475 result.close() 2476 return result.name 2477 2478path_split_name = os.path.split 2479path_basename = os.path.basename 2480path_dirname = os.path.dirname 2481path_absolute = os.path.abspath 2482path_split_extension = os.path.splitext 2483path_resolve = os.path.realpath # fully canonicalizes (& normalizes) a path 2484 2485def path_extension(path): 2486 """Return the extension of a path""" 2487 return os.path.splitext(path)[1] 2488 2489def path_no_extension(path): 2490 """Return the path without an extension""" 2491 return os.path.splitext(path)[0] 2492 2493def path_basename_no_extension(path): 2494 """Return the basename of the path without an extension""" 2495 return path_no_extension(path_basename(path)) 2496 2497def path_split_comps(path): 2498 """Split the path to its components(dir/basenames)""" 2499 comps = [] 2500 while True: 2501 path, comp = path_split_name(path) 2502 if comp: 2503 comps.append(comp) 2504 elif path: 2505 comps.append(path) 2506 else: 2507 break 2508 comps.reverse() 2509 return comps 2510 2511def path_relative(path, base=None, fallback=True): 2512 try: 2513 return os.path.relpath(path, base) 2514 except ValueError: 2515 if fallback: 2516 return path 2517 else: 2518 raise 2519 2520def path_is_inside(path, base): 2521 try: 2522 relpath = path_relative(path, base, fallback=False) 2523 if relpath == ".." or relpath.startswith(".." + os.sep): 2524 return False 2525 return True 2526 except ValueError: 2527 return False 2528 2529def path_modify_time(path): 2530 """Return the modify time of the file/directory at the given path""" 2531 return datetime.fromtimestamp(os.path.getmtime(path)) 2532 2533path_join = os.path.join 2534path_is_absolute = os.path.isabs 2535path_exists = os.path.exists 2536path_is_dir = os.path.isdir 2537path_is_file = os.path.isfile 2538 2539def path_ensure_dir_exists(path): 2540 """If the directory of 'path' doesn't exist, create it""" 2541 dir_ensure_exists(path_dirname(path)) 2542 2543def dir_ensure_exists(path): 2544 """If the directory 'path' doesn't exist, create it""" 2545 try: 2546 os.makedirs(path) 2547 except FileExistsError: 2548 pass 2549 2550def dir_create(path, delete_existing=False): 2551 """Create a directory, optionally deleting any existing files in it first""" 2552 if delete_existing and path_exists(path): 2553 shutil.rmtree(path) 2554 dir_ensure_exists(path) 2555 2556def dir_names(path): 2557 """Return the names of the contents of the directory""" 2558 return os.listdir(path) 2559 2560def dir_paths(path): 2561 """Return the full paths of the contents of the directory""" 2562 return (path_join(path, file) for file in dir_names(path)) 2563 2564dir_get_current = os.getcwd 2565dir_set_current = os.chdir 2566 2567def try_dir_names(path, defval = None): 2568 """Try returning the names of the contents of the directory""" 2569 try: 2570 return dir_names(path) 2571 except Exception: 2572 return defval 2573 2574def try_dir_paths(path, defval = None): 2575 """Try returning the full paths of the contents of the directory""" 2576 try: 2577 return dir_paths(path) 2578 except Exception: 2579 return defval 2580 2581def filename_fixup(filename): 2582 """Fixup a filename to be valid""" 2583 fixed = "".join([ch if ch not in r"\/:*?<>|" else "_" for ch in filename]) 2584 if not fixed or fixed.endswith("."): 2585 fixed += "_" 2586 return fixed 2587 2588def try_cast(value, ctor, defval=None): 2589 """Try converting 'value' via constructor 'ctor', return 'defval' on failure""" 2590 try: 2591 return ctor(value) 2592 except ValueError: 2593 return defval 2594 2595def maybe_int(value, defval=None, base=10): 2596 """Try converting 'value' to an int, return 'defval' on failure""" 2597 if value is None: 2598 return defval 2599 try: 2600 return int(value, base) 2601 except ValueError: 2602 return defval 2603 2604def maybe_float(value, defval=None, base=10): 2605 """Try converting 'value' to a float, return 'defval' on failure""" 2606 if value is None: 2607 return defval 2608 try: 2609 if base == 0: 2610 base = 16 if value.lower().startswith("0x") else 10 2611 2612 if base == 10: 2613 return float(value) 2614 elif base == 16: 2615 return float.fromhex(value) 2616 else: 2617 return defval 2618 except ValueError: 2619 return defval 2620 2621def maybe_num(value, defval=None, base=10): 2622 """Try converting 'value' to an int or float, return 'defval' on failure""" 2623 result = maybe_int(value, base=base) 2624 if result is None: 2625 result = maybe_float(value, base=base) 2626 if result is None: 2627 result = defval 2628 return result 2629 2630def count_significant_bits(a): 2631 """Return how many significant bits (all but leading zero bits) 'a' has""" 2632 assert a >= 0 2633 return a.bit_length() 2634 2635def count_leading_zero_bits(a, bits): 2636 """Return how many leading zero bits 'a' has, counting from 'bits'""" 2637 assert a >= 0 2638 return bits - a.bit_length() 2639 2640def count_trailing_zero_bits(a): 2641 """Return how many trailing zero bits 'a' has""" 2642 assert a >= 0 2643 count = 0 2644 while not (a & 0xff): 2645 count += 8 2646 a >>= 8 2647 while not (a & 0x1): 2648 count += 1 2649 a >>= 1 2650 return count 2651 2652def make_mask(pos, size): 2653 """Create a mask with 'size' ones at bit 'pos'""" 2654 return ((1 << size) - 1) << pos 2655 2656def is_pow2(a): 2657 """Return if 'a' is a power of 2""" 2658 return a > 0 and (a & (a - 1)) == 0 2659 2660def div_up(a, b): 2661 """Divide 'a' by 'b', rounding up""" 2662 r, m = divmod(a, b) 2663 return r + 1 if m else r 2664 2665def quotrem(a, b): 2666 """Return the quotient and remainder of dividing 'a' by 'b'""" 2667 q, r = divmod(a, b) 2668 if q < 0 and r != 0: 2669 q += 1 2670 r -= b 2671 return q, r 2672 2673def quot(a, b): 2674 """Return the quotient of dividing 'a' by 'b'""" 2675 return quotrem(a, b)[0] 2676 2677def rem(a, b): 2678 """Return the remainder of dividing 'a' by 'b'""" 2679 return quotrem(a, b)[1] 2680 2681def round_down(a, b): 2682 """Round 'a' down by 'b'""" 2683 m = a % b 2684 return a - m if m else a 2685 2686def round_up(a, b): 2687 """Round 'a' up by 'b'""" 2688 assert b > 0 2689 m = a % b 2690 return a + (b - m) if m else a 2691 2692def round_up_pow2(a): 2693 """Round 'a' up to its next power of 2""" 2694 assert a > 0 2695 return 1 << (a - 1).bit_length() 2696 2697def sqr(value): 2698 """Square 'value'""" 2699 return value * value 2700 2701def clamp(value, minval, maxval): 2702 """Return 'value' clamped between 'minval' and 'maxval'""" 2703 return minval if value < minval else maxval if value > maxval else value 2704 2705bound = clamp # old/dup name 2706 2707def lerp(start, end, portion): 2708 """Return the linear interpolation between 'start' and 'end'""" 2709 return start + portion * (end - start) 2710 2711def rotate_left(value, count, bits): 2712 """Rotate 'value' left by 'count' bits, across 'bits' bits""" 2713 assert value >= 0 2714 count %= bits 2715 return ((value << count) | (value >> (bits - count))) & make_mask(0, bits) 2716 2717def rotate_right(value, count, bits): 2718 """Rotate 'value' right by 'count' bits, across 'bits' bits""" 2719 assert value >= 0 2720 count %= bits 2721 return ((value >> count) | (value << (bits - count))) & make_mask(0, bits) 2722 2723def closure(__func, *args, **kwargs): 2724 """Create a lambda that applies the given arguments to 'func'""" 2725 return lambda: __func(*args, **kwargs) 2726 2727def debug(*msg): 2728 """Print a message only if debugging is enabled""" 2729 if debug.enabled: 2730 eprint(*msg) 2731 2732debug.enabled = False 2733 2734def warn_assert(cond, msg): 2735 """Warn if 'cond' is false""" 2736 if not cond: 2737 warn(msg) 2738 return cond 2739 2740def fail(msg=None): 2741 """Fail, optionally with message""" 2742 assert False, msg 2743 2744class CheckError(Exception): 2745 """An error meant to be caught and displayed as-is, like AssertionError but for user errors""" 2746 2747def check(cond, msg): 2748 """If condition doesn't hold, raise CheckError""" 2749 if not cond: 2750 raise CheckError(msg) 2751 2752def throw(msg): 2753 """Unconditionally raise CheckError""" 2754 raise CheckError(msg) 2755 2756def desc(value): 2757 """Set a description (desc attr) of the given function""" 2758 def decorator(f): 2759 f.desc = value 2760 return f 2761 return decorator 2762 2763def trace(*args): 2764 """Print with traceback""" 2765 eprint(*args) 2766 traceback.print_stack() 2767 2768def byte(x): 2769 """Return bytes from a single byte""" 2770 return bytes((x,)) 2771 2772def measure_execution_time(func): 2773 """Decorator to measure execution time of a function""" 2774 def decorator(*args, **kwargs): 2775 start = time.time() 2776 result = func(*args, **kwargs) 2777 end = time.time() 2778 eprint(f"{func} took {end - start:f} seconds") 2779 return result 2780 return decorator 2781
32def add_traceback_hook(hook): 33 """adds a hook to be called before printing a traceback, so that the hook can edit it freely""" 34 if not _my_excepthooks: 35 sys.excepthook = _my_excepthook 36 _my_excepthooks.append(hook)
adds a hook to be called before printing a traceback, so that the hook can edit it freely
38def eprint(*args, **kwargs): 39 """like print, but prints to stderr""" 40 print(*args, file=sys.stderr, **kwargs)
like print, but prints to stderr
42def context_manager(method_name = "close"): 43 """Adds __enter__/__exit__ support for a class, using a specified method_name as the 'close' method""" 44 45 def decorator(cls): 46 method = getattr(cls, method_name) 47 48 def __enter__(m): 49 return m 50 def __exit__(m, t, v, s): 51 method(m) 52 53 cls.__enter__ = __enter__ 54 cls.__exit__ = __exit__ 55 return cls 56 return decorator
Adds __enter__/__exit__ support for a class, using a specified method_name as the 'close' method
58def exec_def(name, code, namespace=None): 59 """execute 'code' and extract a definition named 'name' from it""" 60 if namespace is None: 61 namespace = {} 62 exec(code, namespace) 63 return namespace[name]
execute 'code' and extract a definition named 'name' from it
65def exec_script_by_path(path, name=None): 66 """executes script at 'path', returning its module object""" 67 import importlib.util 68 script_spec = importlib.util.spec_from_file_location(default(name, path_basename_no_extension(path)), path_absolute(path)) 69 script_mod = importlib.util.module_from_spec(script_spec) 70 script_spec.loader.exec_module(script_mod) 71 return script_mod
executes script at 'path', returning its module object
returns the name of the object's type
77class Dynamic(object): 78 """An anonymous dynamic class with keyword-args-style initialization""" 79 80 def __init__(__m_, **__kw_): 81 __m_.__dict__ = __kw_ 82 83 @recursive_repr() 84 def __repr__(m): 85 contents = ", ".join(f"{k}={repr(v)}" for k, v in m.__dict__.items()) 86 return f"{typename(m)}({contents})"
An anonymous dynamic class with keyword-args-style initialization
88class DefaultDynamic(Dynamic): 89 """Like Dynamic, but accessing an unknown key gives None""" 90 91 def __getattr__(m, name): 92 return None
Like Dynamic, but accessing an unknown key gives None
94def isdescriptor(obj): 95 """Return whether the value is a descriptor""" 96 return hasattr(obj, "__get__") or hasattr(obj, "__set__") or hasattr(obj, "__del__")
Return whether the value is a descriptor
98class IncludeAttr: 99 """When defining an Enum/Tuple/etc, forces the attribute to be included, despite having a private name or being a function/descriptor/...""" 100 def __init__(m, value): 101 m.value = value
When defining an Enum/Tuple/etc, forces the attribute to be included, despite having a private name or being a function/descriptor/...
103class NoRenameAttr(IncludeAttr): 104 """When defining an Enum/Tuple/etc, forces the attribute to be included and not be renamed, despite having a name ending in _""" 105 def __init__(m, value): 106 m.value = value
When defining an Enum/Tuple/etc, forces the attribute to be included and not be renamed, despite having a name ending in _
108class ExcludeAttr: 109 """When defining an Enum/Tuple/etc, forces the attribute to be excluded, despite not having a private name nad not being a function/descriptor/...""" 110 def __init__(m, value): 111 m.value = value
When defining an Enum/Tuple/etc, forces the attribute to be excluded, despite not having a private name nad not being a function/descriptor/...
149class EnumMetaclass(type): 150 def __new__(meta, cls_name, cls_bases, cls_dict, _values=None): 151 if not cls_bases or Enum not in cls_bases: 152 return super().__new__(meta, cls_name, cls_bases, cls_dict) 153 154 # collect 155 enum_bases = tuple(base for base in cls_bases if base is not Enum and base.__class__ == EnumMetaclass) 156 157 first_auto = None if enum_bases else 0 158 def next_auto(prev): 159 if not isinstance(prev, (int, float)): 160 raise Exception(f"Cannot follow {prev} with ...") 161 return prev + 1 162 163 name_value_map = dict(_metaclass_collect_values(cls_dict, _values, first_auto, next_auto)) 164 165 full_name_value_map = name_value_map.copy() if enum_bases else name_value_map 166 for base in enum_bases: 167 full_name_value_map.update(base._values) 168 169 full_value_name_map = {v:k for k,v in full_name_value_map.items()} 170 171 # dict 172 def __init__(m, value): 173 if value in full_value_name_map: 174 m.value = value 175 elif value in full_name_value_map: 176 m.value = full_name_value_map[value] 177 else: 178 raise ValueError(f"{value} not value of {cls_name}") 179 180 def __eq__(m, other): 181 if m.__class__ != other.__class__: 182 return NotImplemented 183 return m.value == other.value 184 185 def __lt__(m, other): 186 if not isinstance(m, other.__class__) and not isinstance(other, m.__class__): 187 return NotImplemented 188 return m.value < other.value 189 190 def __str__(m): 191 return full_value_name_map[m.value] 192 193 def __repr__(m): 194 return f"{cls_name}.{full_value_name_map[m.value]}" 195 196 def __int__(m): 197 return m.value 198 199 def __bool__(m): 200 return m.value != 0 201 202 def __hash__(m): 203 return hash(m.value) 204 205 enum_dict = {} 206 enum_dict["__init__"] = __init__ 207 enum_dict["__eq__"] = __eq__ 208 enum_dict["__lt__"] = __lt__ 209 enum_dict["__str__"] = __str__ 210 enum_dict["__repr__"] = __repr__ 211 enum_dict["__int__"] = __int__ 212 enum_dict["__bool__"] = __bool__ 213 enum_dict["__hash__"] = __hash__ 214 enum_dict["__slots__"] = ("value",) 215 enum_dict["_values"] = full_name_value_map 216 217 for k, v in cls_dict.items(): 218 if isinstance(v, ExcludeAttr): 219 v = v.value 220 221 if k in name_value_map: 222 continue 223 elif k == "__slots__": 224 enum_dict[k] = enum_dict[k] + (v if isinstance(v, tuple) else (v,)) 225 elif k in enum_dict: 226 raise Exception(f"Cannot set {k} in Enum (but can override in inherited classes)") 227 else: 228 enum_dict[k] = v 229 230 enum_class = super().__new__(meta, cls_name, cls_bases, enum_dict) 231 232 for k, v in name_value_map.items(): 233 setattr(enum_class, k, enum_class(v)) 234 235 enum_class = total_ordering(enum_class) 236 return enum_class
type(object) -> the object's type type(name, bases, dict, **kwds) -> a new type
238class Enum(metaclass=EnumMetaclass): 239 """If a class has Enum as a baseclass, it's transformed into an enum. 240 All non-private attributes of the class other than functions and descriptors become enum members. 241 Atributes with a value of ... receive values automatically. 242 Inherited classes behave like regular classes unless they have Enum as a direct baseclass. 243 Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter 244 Atributes with a name ending with _ can be referred to without the _. 245 """ 246 __slots__ = ()
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 _.
248class BitmaskMetaclass(type): 249 def __new__(meta, cls_name, cls_bases, cls_dict, _values=None): 250 if not cls_bases or Bitmask not in cls_bases: 251 return super().__new__(meta, cls_name, cls_bases, cls_dict) 252 253 # collect 254 bitmask_bases = tuple(base for base in cls_bases if base is not Bitmask and base.__class__ == BitmaskMetaclass) 255 256 first_auto = None if bitmask_bases else 0 257 def next_auto(prev): 258 if not isinstance(prev, int) or (prev != 0 and not is_pow2(prev)): 259 raise Exception(f"Cannot follow {prev} with ...") 260 return prev << 1 if prev != 0 else 1 261 262 name_mask_map = dict(_metaclass_collect_values(cls_dict, _values, first_auto, next_auto)) 263 264 full_name_mask_map = name_mask_map.copy() if bitmask_bases else name_mask_map 265 for base in bitmask_bases: 266 full_name_mask_map.update(base._fields) 267 268 full_mask_name_map = {v:k for k,v in full_name_mask_map.items()} 269 full_mask = reduce(lambda x,y:x|y, full_mask_name_map.keys(), 0) 270 271 # dict 272 def __init__(m, value = None, **kwargs): 273 if value is None: 274 m.value = 0 275 elif isinstance(value, int) and (value & full_mask) == value: 276 m.value = value 277 elif isinstance(value, str) and value in full_name_mask_map: 278 m.value = full_name_mask_map[value] 279 elif isinstance(value, m.__class__): 280 m.value = value.value 281 elif isinstance(value, (tuple, list)): 282 m.value = reduce(lambda x,y:x|y, (full_name_mask_map[part] for part in value), 0) 283 else: 284 raise ValueError(f"{value} not value of {cls_name}") 285 286 if kwargs: 287 for key, value in kwargs.items(): 288 setattr(m, key, value) 289 290 def __eq__(m, other): 291 if m.__class__ != other.__class__: 292 return NotImplemented 293 return m.value == other.value 294 295 def __hash__(m): 296 return hash(m.value) 297 298 def __str__(m): 299 if m.value: 300 values = [] 301 for mask, name in full_mask_name_map.items(): 302 if m.value & mask: 303 values.append(name) 304 305 return ",".join(values) 306 else: 307 return "" 308 309 def __repr__(m): 310 if m.value: 311 values = [] 312 for mask, name in full_mask_name_map.items(): 313 if m.value & mask: 314 values.append(f"{cls_name}.{name}") 315 316 return " | ".join(values) 317 else: 318 return f"{cls_name}(0)" 319 320 def __int__(m): 321 return m.value 322 323 def __bool__(m): 324 return m.value != 0 325 326 def __and__(m, other): 327 if m.__class__ != other.__class__: 328 return NotImplemented 329 return m.__class__(m.value & other.value) 330 331 def __or__(m, other): 332 if m.__class__ != other.__class__: 333 return NotImplemented 334 return m.__class__(m.value | other.value) 335 336 def __xor__(m, other): 337 if m.__class__ != other.__class__: 338 return NotImplemented 339 return m.__class__(m.value ^ other.value) 340 341 class no_bits_property: 342 def __init__(m, mask): 343 m.mask = mask 344 345 def __get__(m, obj, cls): 346 if obj is None: 347 return cls(m.mask) 348 else: 349 raise AttributeError() 350 351 def __set__(m, obj, value): 352 raise AttributeError() 353 354 class bit_property: 355 def __init__(m, mask): 356 m.mask = mask 357 358 def __get__(m, obj, cls): 359 if obj is None: 360 return cls(m.mask) 361 else: 362 return bool(obj.value & m.mask) 363 364 def __set__(m, obj, value): 365 if value: 366 obj.value |= m.mask 367 else: 368 obj.value &= ~m.mask 369 370 class bitfield_property: 371 def __init__(m, mask): 372 m.mask = mask 373 m.shift = count_trailing_zero_bits(mask) 374 375 def __get__(m, obj, cls): 376 if obj is None: 377 return cls(m.mask) 378 else: 379 return (obj.value & m.mask) >> m.shift 380 381 def __set__(m, obj, value): 382 obj.value = (obj.value & ~m.mask) | ((value << m.shift) & m.mask) 383 384 class typed_bitfield_property: 385 def __init__(m, mask, type): 386 m.mask, m.type = mask, type 387 m.shift = count_trailing_zero_bits(mask) 388 389 def __get__(m, obj, cls): 390 if obj is None: 391 return cls(m.mask) 392 else: 393 return m.type((obj.value & m.mask) >> m.shift) 394 395 def __set__(m, obj, value): 396 obj.value = (obj.value & ~m.mask) | ((int(value) << m.shift) & m.mask) 397 398 bitmask_dict = {} 399 bitmask_dict["__init__"] = __init__ 400 bitmask_dict["__eq__"] = __eq__ 401 bitmask_dict["__hash__"] = __hash__ 402 bitmask_dict["__str__"] = __str__ 403 bitmask_dict["__repr__"] = __repr__ 404 bitmask_dict["__int__"] = __int__ 405 bitmask_dict["__bool__"] = __bool__ 406 bitmask_dict["__and__"] = __and__ 407 bitmask_dict["__or__"] = __or__ 408 bitmask_dict["__xor__"] = __xor__ 409 bitmask_dict["__slots__"] = ("value",) 410 bitmask_dict["_fields"] = full_name_mask_map 411 412 annots = get_meta_annotations(cls_dict) 413 414 for name, mask in name_mask_map.items(): 415 if annots and name in annots: 416 bitmask_dict[name] = typed_bitfield_property(mask, annots[name]) 417 elif mask == 0: 418 bitmask_dict[name] = no_bits_property(mask) 419 elif is_pow2(mask): 420 bitmask_dict[name] = bit_property(mask) 421 else: 422 bitmask_dict[name] = bitfield_property(mask) 423 424 for k, v in cls_dict.items(): 425 if isinstance(v, ExcludeAttr): 426 v = v.value 427 428 if k in name_mask_map: 429 continue 430 elif k == "__slots__": 431 bitmask_dict[k] = bitmask_dict[k] + (v if isinstance(v, tuple) else (v,)) 432 elif k in bitmask_dict: 433 raise Exception(f"Cannot set {k} in Bitmask (but can override in inherited classes)") 434 else: 435 bitmask_dict[k] = v 436 437 return super().__new__(meta, cls_name, cls_bases, bitmask_dict)
type(object) -> the object's type type(name, bases, dict, **kwds) -> a new type
439class Bitmask(metaclass=BitmaskMetaclass): 440 """If a class has Bitmask as a baseclass, it's transformed into a bitmask. 441 All non-private attributes of the class other than functions and descriptors become bitmask fields. 442 Atributes with a value of ... receive bits automatically. 443 A bitmask is like a struct, but with its fields mapped into a single bitmask integer. 444 Bitmasks can also be manipulated via: & | ^ 445 Inherited classes behave like regular classes unless they have Bitmask as a direct baseclass. 446 Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter 447 Atributes with a name ending with _ can be referred to without the _. 448 """ 449 __slots__ = ()
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 _.
467class TupleMetaclass(type): 468 def __new__(meta, cls_name, cls_bases, cls_dict, _values=None, **consts): 469 if not cls_bases or cls_bases == (tuple,) or Tuple not in cls_bases: 470 return super().__new__(meta, cls_name, cls_bases, cls_dict) 471 472 # collect 473 tuple_bases = tuple(base for base in cls_bases if base is not Tuple and base.__class__ == TupleMetaclass) 474 if len(tuple_bases) > 1: 475 raise Exception("Tuples cannot have multiple Tuple baseclasses") 476 477 fields, defaults = _metaclass_collect_fields(cls_dict, _values) 478 479 all_fields, all_defaults = _metaclass_collect_from_bases(fields, defaults, tuple_bases, is_new=True) 480 481 # dict 482 field_params_str = ', '.join(f for f in all_fields if f not in consts) 483 field_values_str = ', '.join(all_fields) + ("," if len(all_fields) == 1 else "") 484 new_def = f"def __new__(__cls, {field_params_str}):\n" 485 new_def += f" return tuple.__new__(__cls, ({field_values_str}))\n" 486 __new__ = exec_def("__new__", new_def, consts) 487 __new__.__defaults__ = all_defaults 488 489 def __reduce_ex__(m, proto): 490 return (m.__new__, (m.__class__, *m)) 491 492 @recursive_repr() 493 def __repr__(m): 494 contents = ", ".join(f"{f}={repr(getattr(m, f))}" for f in m._fields) 495 return f"{cls_name}({contents})" 496 497 def _replace(m, **changes): 498 return m.__class__(*map(changes.pop, m._fields, m)) 499 500 tuple_dict = {} 501 tuple_dict["__new__"] = __new__ 502 tuple_dict["__reduce_ex__"] = __reduce_ex__ 503 tuple_dict["__repr__"] = __repr__ 504 tuple_dict["__slots__"] = () # fields come from tuple 505 tuple_dict["_replace"] = _replace 506 tuple_dict["_fields"] = all_fields 507 508 start = len(all_fields) - len(fields) 509 for i, field in enumerate(fields): 510 tuple_dict[field] = property(operator.itemgetter(start + i)) 511 512 fields_set = set(fields) 513 514 for k, v in cls_dict.items(): 515 if isinstance(v, ExcludeAttr): 516 v = v.value 517 518 if k in fields_set: 519 continue 520 elif k == "__slots__": 521 tuple_dict[k] = tuple_dict[k] + (v if isinstance(v, tuple) else (v,)) 522 elif k in tuple_dict: 523 raise Exception(f"Cannot set {k} in Tuple (but can override in inherited classes)") 524 else: 525 tuple_dict[k] = v 526 527 return super().__new__(meta, cls_name, cls_bases, tuple_dict)
type(object) -> the object's type type(name, bases, dict, **kwds) -> a new type
529class Tuple(tuple, metaclass=TupleMetaclass): 530 """If a class has Tuple as a baseclass, it's transformed into a named tuple. 531 All non-private attributes of the class other than functions and descriptors become tuple fields. 532 Atributes with a value of ... are required, otherwise - optional with the given default value. 533 The tuple behaves similarly to collections.namedtuple 534 Inherited classes behave like regular classes unless they have Tuple as a direct baseclass. 535 Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter, const base fields keyword parameters 536 Atributes with a name ending with _ can be referred to without the _. 537 """ 538 __slots__ = ()
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, const base fields keyword parameters Atributes with a name ending with _ can be referred to without the _.
540class StructMetaclass(type): 541 def __new__(meta, cls_name, cls_bases, cls_dict, _values=None, **consts): 542 if not cls_bases or Struct not in cls_bases: 543 return super().__new__(meta, cls_name, cls_bases, cls_dict) 544 545 # collect 546 struct_bases = tuple(base for base in cls_bases if base is not Struct and base.__class__ == StructMetaclass) 547 if len(struct_bases) > 1: 548 raise Exception("Structs cannot have multiple Struct baseclasses") 549 550 fields, defaults = _metaclass_collect_fields(cls_dict, _values) 551 552 all_fields, all_defaults = _metaclass_collect_from_bases(fields, defaults, struct_bases) 553 554 # dict 555 init_def = f"def __init__(__m, {', '.join(f for f in all_fields if f not in consts)}):\n" 556 for field in all_fields: 557 init_def += f" __m.{field} = {field}\n" 558 if not all_fields: 559 init_def += " pass" 560 __init__ = exec_def("__init__", init_def, consts) 561 __init__.__defaults__ = all_defaults 562 563 @recursive_repr() 564 def __repr__(m): 565 contents = ", ".join(f"{f}={repr(getattr(m, f))}" for f in m._fields) 566 return f"{cls_name}({contents})" 567 568 # note - equality is by-identity (unless option to control is added?) 569 570 struct_dict = {} 571 struct_dict["__init__"] = __init__ 572 struct_dict["__repr__"] = __repr__ 573 struct_dict["__slots__"] = fields 574 struct_dict["_fields"] = all_fields 575 576 fields_set = set(fields) 577 578 for k, v in cls_dict.items(): 579 if isinstance(v, ExcludeAttr): 580 v = v.value 581 582 if k in fields_set: 583 continue 584 elif k == "__slots__": 585 struct_dict[k] = struct_dict[k] + (v if isinstance(v, tuple) else (v,)) 586 elif k in struct_dict: 587 raise Exception(f"Cannot set {k} in Struct (but can override in inherited classes)") 588 else: 589 struct_dict[k] = v 590 591 return super().__new__(meta, cls_name, cls_bases, struct_dict)
type(object) -> the object's type type(name, bases, dict, **kwds) -> a new type
593class Struct(metaclass=StructMetaclass): 594 """If a class has Struct as a baseclass, it's transformed into a struct. 595 All non-private attributes of the class other than functions and descriptors become struct fields. 596 Atributes with a value of ... are required, otherwise - optional with the given default value. 597 A struct is like a mutable named tuple, except equality goes by identity. 598 Inherited classes behave like regular classes unless they have Struct as a direct baseclass. 599 Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter, const base fields keyword parameters 600 Atributes with a name ending with _ can be referred to without the _. 601 """ 602 __slots__ = ()
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, const base fields keyword parameters Atributes with a name ending with _ can be referred to without the _.
604def SymbolClass(name): 605 """Create a class with the given name that returns cached symbols when invoked""" 606 class cls(object): 607 __slots__ = 'value' 608 cache = {} 609 610 def __new__(cls, value): 611 ident = cls.cache.get(value) 612 if ident is None: 613 ident = super().__new__(cls) 614 ident.value = value 615 cls.cache[value] = ident 616 return ident 617 618 def __str__(m): 619 return str(m.value) 620 def __bytes__(m): 621 return bytes(m.value) 622 def __repr__(m): 623 return f"`{m.value}" 624 625 cls.__name__ = name 626 return cls
Create a class with the given name that returns cached symbols when invoked
630class classproperty(object): 631 """Method decorator that turns it into a read-only class property""" 632 633 def __init__(m, func): 634 m.getter = func 635 636 def __get__(m, _, cls): 637 return m.getter(cls) 638 639 # must be read-only, sadly
Method decorator that turns it into a read-only class property
641class staticproperty(object): 642 """Method decorator that turns it into a read-only static property""" 643 644 def __init__(m, func): 645 m.getter = func 646 647 def __get__(m, _, cls): 648 return m.getter() 649 650 # must be read-only, sadly
Method decorator that turns it into a read-only static property
652class writeonly_property(object): 653 """Method decorator that turns it into a write-only property""" 654 655 def __init__(m, func): 656 m.func = func 657 658 def __set__(m, obj, value): 659 return m.func(obj, value)
Method decorator that turns it into a write-only property
663class lazy_property(object): 664 """Method decorator that turns it into a lazily-evaluated property""" 665 666 def __init__(m, func): 667 m.func = func 668 669 def __get__(m, obj, cls): 670 if obj is None: 671 return m 672 else: 673 value = m.func(obj) 674 obj.__dict__[m.func.__name__] = value # won't be called again for this obj 675 return value 676 677 @staticmethod 678 def is_set(obj, name): 679 return name in obj.__dict__ 680 681 @staticmethod 682 def clear(obj, name): 683 obj.__dict__.pop(name, None)
Method decorator that turns it into a lazily-evaluated property
685class lazy_classproperty(object): 686 """Method decorator that turns it into a lazily-evaluated class property""" 687 688 def __init__(m, func): 689 m.func = func 690 691 def __get__(m, _, cls): 692 value = m.func(cls) 693 setattr(cls, m.func.__name__, value) # won't be called again for this obj 694 return value
Method decorator that turns it into a lazily-evaluated class property
696class lazy_staticproperty(object): 697 """Method decorator that turns it into a lazily-evaluated static property""" 698 699 def __init__(m, func): 700 m.func = func 701 702 def __get__(m, _, cls): 703 value = m.func() 704 setattr(cls, m.func.__name__, value) # won't be called again for this obj 705 return value
Method decorator that turns it into a lazily-evaluated static property
707class post_property_set(object): 708 """Method decorator that creates a field-backed read-write property that calls the 709 decorated method when set, with the old and new values""" 710 711 def __init__(m, post_func): 712 m.post_func = post_func 713 m.attr = "_" + post_func.__name__ 714 715 def __get__(m, obj, t = None): 716 try: 717 if obj is None: 718 return m 719 else: 720 return getattr(obj, m.attr) 721 except AttributeError: 722 return None 723 724 def __set__(m, obj, value): 725 old_value = m.__get__(obj) 726 setattr(obj, m.attr, value) 727 m.post_func(obj, old_value, value)
Method decorator that creates a field-backed read-write property that calls the decorated method when set, with the old and new values
729class post_property_change(post_property_set): 730 """Method decorator that creates a field-backed read-write property that calls the 731 decorated method when changed (going by == equality), with the old and new values""" 732 733 def __set__(m, obj, value): 734 old_value = m.__get__(obj) 735 changed = old_value != value 736 737 if changed: 738 setattr(obj, m.attr, value) 739 m.post_func(obj, old_value, value)
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
Inherited Members
741def staticclass(cls): 742 """Class decorator that turns all methods into static methods, and properties into static properties""" 743 for name, value in getattrs(cls): 744 if callable(value): 745 setattr(cls, name, staticmethod(value)) 746 elif isinstance(value, property): 747 setattr(cls, name, staticproperty(value.fget)) 748 elif isinstance(value, lazy_property): 749 setattr(cls, name, lazy_staticproperty(value.func)) 750 return cls
Class decorator that turns all methods into static methods, and properties into static properties
defaultdict(default_factory=None, /, [...]) --> dict with default factory
The default factory is called without arguments to produce a new value when a key is not present, in __getitem__ only. A defaultdict compares equal to a dict with the same items. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.
A list-like sequence optimized for data accesses near its endpoints.
299class WeakKeyDictionary(_collections_abc.MutableMapping): 300 """ Mapping class that references keys weakly. 301 302 Entries in the dictionary will be discarded when there is no 303 longer a strong reference to the key. This can be used to 304 associate additional data with an object owned by other parts of 305 an application without adding attributes to those objects. This 306 can be especially useful with objects that override attribute 307 accesses. 308 """ 309 310 def __init__(self, dict=None): 311 self.data = {} 312 def remove(k, selfref=ref(self)): 313 self = selfref() 314 if self is not None: 315 try: 316 del self.data[k] 317 except KeyError: 318 pass 319 self._remove = remove 320 if dict is not None: 321 self.update(dict) 322 323 def __delitem__(self, key): 324 del self.data[ref(key)] 325 326 def __getitem__(self, key): 327 return self.data[ref(key)] 328 329 def __len__(self): 330 return len(self.data) 331 332 def __repr__(self): 333 return "<%s at %#x>" % (self.__class__.__name__, id(self)) 334 335 def __setitem__(self, key, value): 336 self.data[ref(key, self._remove)] = value 337 338 def copy(self): 339 new = WeakKeyDictionary() 340 for key, value in self.data.copy().items(): 341 o = key() 342 if o is not None: 343 new[o] = value 344 return new 345 346 __copy__ = copy 347 348 def __deepcopy__(self, memo): 349 from copy import deepcopy 350 new = self.__class__() 351 for key, value in self.data.copy().items(): 352 o = key() 353 if o is not None: 354 new[o] = deepcopy(value, memo) 355 return new 356 357 def get(self, key, default=None): 358 return self.data.get(ref(key),default) 359 360 def __contains__(self, key): 361 try: 362 wr = ref(key) 363 except TypeError: 364 return False 365 return wr in self.data 366 367 def items(self): 368 for wr, value in self.data.copy().items(): 369 key = wr() 370 if key is not None: 371 yield key, value 372 373 def keys(self): 374 for wr in self.data.copy(): 375 obj = wr() 376 if obj is not None: 377 yield obj 378 379 __iter__ = keys 380 381 def values(self): 382 for wr, value in self.data.copy().items(): 383 if wr() is not None: 384 yield value 385 386 def keyrefs(self): 387 """Return a list of weak references to the keys. 388 389 The references are not guaranteed to be 'live' at the time 390 they are used, so the result of calling the references needs 391 to be checked before being used. This can be used to avoid 392 creating references that will cause the garbage collector to 393 keep the keys around longer than needed. 394 395 """ 396 return list(self.data) 397 398 def popitem(self): 399 while True: 400 key, value = self.data.popitem() 401 o = key() 402 if o is not None: 403 return o, value 404 405 def pop(self, key, *args): 406 return self.data.pop(ref(key), *args) 407 408 def setdefault(self, key, default=None): 409 return self.data.setdefault(ref(key, self._remove),default) 410 411 def update(self, dict=None, /, **kwargs): 412 d = self.data 413 if dict is not None: 414 if not hasattr(dict, "items"): 415 dict = type({})(dict) 416 for key, value in dict.items(): 417 d[ref(key, self._remove)] = value 418 if len(kwargs): 419 self.update(kwargs) 420 421 def __ior__(self, other): 422 self.update(other) 423 return self 424 425 def __or__(self, other): 426 if isinstance(other, _collections_abc.Mapping): 427 c = self.copy() 428 c.update(other) 429 return c 430 return NotImplemented 431 432 def __ror__(self, other): 433 if isinstance(other, _collections_abc.Mapping): 434 c = self.__class__() 435 c.update(other) 436 c.update(self) 437 return c 438 return NotImplemented
Mapping class that references keys weakly.
Entries in the dictionary will be discarded when there is no longer a strong reference to the key. This can be used to associate additional data with an object owned by other parts of an application without adding attributes to those objects. This can be especially useful with objects that override attribute accesses.
367 def items(self): 368 for wr, value in self.data.copy().items(): 369 key = wr() 370 if key is not None: 371 yield key, value
D.items() -> a set-like object providing a view on D's items
373 def keys(self): 374 for wr in self.data.copy(): 375 obj = wr() 376 if obj is not None: 377 yield obj
D.keys() -> a set-like object providing a view on D's keys
381 def values(self): 382 for wr, value in self.data.copy().items(): 383 if wr() is not None: 384 yield value
D.values() -> an object providing a view on D's values
386 def keyrefs(self): 387 """Return a list of weak references to the keys. 388 389 The references are not guaranteed to be 'live' at the time 390 they are used, so the result of calling the references needs 391 to be checked before being used. This can be used to avoid 392 creating references that will cause the garbage collector to 393 keep the keys around longer than needed. 394 395 """ 396 return list(self.data)
Return a list of weak references to the keys.
The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the keys around longer than needed.
398 def popitem(self): 399 while True: 400 key, value = self.data.popitem() 401 o = key() 402 if o is not None: 403 return o, value
D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty.
D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
408 def setdefault(self, key, default=None): 409 return self.data.setdefault(ref(key, self._remove),default)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
411 def update(self, dict=None, /, **kwargs): 412 d = self.data 413 if dict is not None: 414 if not hasattr(dict, "items"): 415 dict = type({})(dict) 416 for key, value in dict.items(): 417 d[ref(key, self._remove)] = value 418 if len(kwargs): 419 self.update(kwargs)
D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. If E present and has a .keys() method, does: for k in E.keys(): D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
93class WeakValueDictionary(_collections_abc.MutableMapping): 94 """Mapping class that references values weakly. 95 96 Entries in the dictionary will be discarded when no strong 97 reference to the value exists anymore 98 """ 99 # We inherit the constructor without worrying about the input 100 # dictionary; since it uses our .update() method, we get the right 101 # checks (if the other dictionary is a WeakValueDictionary, 102 # objects are unwrapped on the way out, and we always wrap on the 103 # way in). 104 105 def __init__(self, other=(), /, **kw): 106 def remove(wr, selfref=ref(self), _atomic_removal=_remove_dead_weakref): 107 self = selfref() 108 if self is not None: 109 # Atomic removal is necessary since this function 110 # can be called asynchronously by the GC 111 _atomic_removal(self.data, wr.key) 112 self._remove = remove 113 self.data = {} 114 self.update(other, **kw) 115 116 def __getitem__(self, key): 117 o = self.data[key]() 118 if o is None: 119 raise KeyError(key) 120 else: 121 return o 122 123 def __delitem__(self, key): 124 del self.data[key] 125 126 def __len__(self): 127 return len(self.data) 128 129 def __contains__(self, key): 130 try: 131 o = self.data[key]() 132 except KeyError: 133 return False 134 return o is not None 135 136 def __repr__(self): 137 return "<%s at %#x>" % (self.__class__.__name__, id(self)) 138 139 def __setitem__(self, key, value): 140 self.data[key] = KeyedRef(value, self._remove, key) 141 142 def copy(self): 143 new = WeakValueDictionary() 144 for key, wr in self.data.copy().items(): 145 o = wr() 146 if o is not None: 147 new[key] = o 148 return new 149 150 __copy__ = copy 151 152 def __deepcopy__(self, memo): 153 from copy import deepcopy 154 new = self.__class__() 155 for key, wr in self.data.copy().items(): 156 o = wr() 157 if o is not None: 158 new[deepcopy(key, memo)] = o 159 return new 160 161 def get(self, key, default=None): 162 try: 163 wr = self.data[key] 164 except KeyError: 165 return default 166 else: 167 o = wr() 168 if o is None: 169 # This should only happen 170 return default 171 else: 172 return o 173 174 def items(self): 175 for k, wr in self.data.copy().items(): 176 v = wr() 177 if v is not None: 178 yield k, v 179 180 def keys(self): 181 for k, wr in self.data.copy().items(): 182 if wr() is not None: 183 yield k 184 185 __iter__ = keys 186 187 def itervaluerefs(self): 188 """Return an iterator that yields the weak references to the values. 189 190 The references are not guaranteed to be 'live' at the time 191 they are used, so the result of calling the references needs 192 to be checked before being used. This can be used to avoid 193 creating references that will cause the garbage collector to 194 keep the values around longer than needed. 195 196 """ 197 yield from self.data.copy().values() 198 199 def values(self): 200 for wr in self.data.copy().values(): 201 obj = wr() 202 if obj is not None: 203 yield obj 204 205 def popitem(self): 206 while True: 207 key, wr = self.data.popitem() 208 o = wr() 209 if o is not None: 210 return key, o 211 212 def pop(self, key, *args): 213 try: 214 o = self.data.pop(key)() 215 except KeyError: 216 o = None 217 if o is None: 218 if args: 219 return args[0] 220 else: 221 raise KeyError(key) 222 else: 223 return o 224 225 def setdefault(self, key, default=None): 226 try: 227 o = self.data[key]() 228 except KeyError: 229 o = None 230 if o is None: 231 self.data[key] = KeyedRef(default, self._remove, key) 232 return default 233 else: 234 return o 235 236 def update(self, other=None, /, **kwargs): 237 d = self.data 238 if other is not None: 239 if not hasattr(other, "items"): 240 other = dict(other) 241 for key, o in other.items(): 242 d[key] = KeyedRef(o, self._remove, key) 243 for key, o in kwargs.items(): 244 d[key] = KeyedRef(o, self._remove, key) 245 246 def valuerefs(self): 247 """Return a list of weak references to the values. 248 249 The references are not guaranteed to be 'live' at the time 250 they are used, so the result of calling the references needs 251 to be checked before being used. This can be used to avoid 252 creating references that will cause the garbage collector to 253 keep the values around longer than needed. 254 255 """ 256 return list(self.data.copy().values()) 257 258 def __ior__(self, other): 259 self.update(other) 260 return self 261 262 def __or__(self, other): 263 if isinstance(other, _collections_abc.Mapping): 264 c = self.copy() 265 c.update(other) 266 return c 267 return NotImplemented 268 269 def __ror__(self, other): 270 if isinstance(other, _collections_abc.Mapping): 271 c = self.__class__() 272 c.update(other) 273 c.update(self) 274 return c 275 return NotImplemented
Mapping class that references values weakly.
Entries in the dictionary will be discarded when no strong reference to the value exists anymore
105 def __init__(self, other=(), /, **kw): 106 def remove(wr, selfref=ref(self), _atomic_removal=_remove_dead_weakref): 107 self = selfref() 108 if self is not None: 109 # Atomic removal is necessary since this function 110 # can be called asynchronously by the GC 111 _atomic_removal(self.data, wr.key) 112 self._remove = remove 113 self.data = {} 114 self.update(other, **kw)
161 def get(self, key, default=None): 162 try: 163 wr = self.data[key] 164 except KeyError: 165 return default 166 else: 167 o = wr() 168 if o is None: 169 # This should only happen 170 return default 171 else: 172 return o
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
174 def items(self): 175 for k, wr in self.data.copy().items(): 176 v = wr() 177 if v is not None: 178 yield k, v
D.items() -> a set-like object providing a view on D's items
187 def itervaluerefs(self): 188 """Return an iterator that yields the weak references to the values. 189 190 The references are not guaranteed to be 'live' at the time 191 they are used, so the result of calling the references needs 192 to be checked before being used. This can be used to avoid 193 creating references that will cause the garbage collector to 194 keep the values around longer than needed. 195 196 """ 197 yield from self.data.copy().values()
Return an iterator that yields the weak references to the values.
The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the values around longer than needed.
199 def values(self): 200 for wr in self.data.copy().values(): 201 obj = wr() 202 if obj is not None: 203 yield obj
D.values() -> an object providing a view on D's values
205 def popitem(self): 206 while True: 207 key, wr = self.data.popitem() 208 o = wr() 209 if o is not None: 210 return key, o
D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty.
212 def pop(self, key, *args): 213 try: 214 o = self.data.pop(key)() 215 except KeyError: 216 o = None 217 if o is None: 218 if args: 219 return args[0] 220 else: 221 raise KeyError(key) 222 else: 223 return o
D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
225 def setdefault(self, key, default=None): 226 try: 227 o = self.data[key]() 228 except KeyError: 229 o = None 230 if o is None: 231 self.data[key] = KeyedRef(default, self._remove, key) 232 return default 233 else: 234 return o
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
236 def update(self, other=None, /, **kwargs): 237 d = self.data 238 if other is not None: 239 if not hasattr(other, "items"): 240 other = dict(other) 241 for key, o in other.items(): 242 d[key] = KeyedRef(o, self._remove, key) 243 for key, o in kwargs.items(): 244 d[key] = KeyedRef(o, self._remove, key)
D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. If E present and has a .keys() method, does: for k in E.keys(): D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
246 def valuerefs(self): 247 """Return a list of weak references to the values. 248 249 The references are not guaranteed to be 'live' at the time 250 they are used, so the result of calling the references needs 251 to be checked before being used. This can be used to avoid 252 creating references that will cause the garbage collector to 253 keep the values around longer than needed. 254 255 """ 256 return list(self.data.copy().values())
Return a list of weak references to the values.
The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the values around longer than needed.
759class LazyDict(defaultdict): 760 """Dict that populates entries lazily via a function that takes the key as the argument""" 761 762 def __init__(m, populate): 763 m.populate = populate 764 defaultdict.__init__(m) 765 766 def __missing__(m, key): 767 value = m.populate(key) 768 m[key] = value 769 return value
Dict that populates entries lazily via a function that takes the key as the argument
771class OrderByKey: 772 """Implements ordering and equality based on order_key()""" 773 # def order_key(m): 774 def order_type(m): return type(m) 775 776 def __eq__(m, other): 777 if isinstance(other, m.order_type()): 778 return m.order_key() == other.order_key() 779 else: 780 return NotImplemented 781 def __ne__(m, other): 782 if isinstance(other, m.order_type()): 783 return m.order_key() != other.order_key() 784 else: 785 return NotImplemented 786 def __lt__(m, other): 787 if isinstance(other, m.order_type()): 788 return m.order_key() < other.order_key() 789 else: 790 return NotImplemented 791 def __gt__(m, other): 792 if isinstance(other, m.order_type()): 793 return m.order_key() > other.order_key() 794 else: 795 return NotImplemented 796 def __le__(m, other): 797 if isinstance(other, m.order_type()): 798 return m.order_key() <= other.order_key() 799 else: 800 return NotImplemented 801 def __ge__(m, other): 802 if isinstance(other, m.order_type()): 803 return m.order_key() >= other.order_key() 804 else: 805 return NotImplemented
Implements ordering and equality based on order_key()
850@context_manager("close") 851class BinaryBase(object): 852 def close(m): 853 m.f.close() 854 855 def len(m): 856 old_pos = m.pos() 857 m.unwind() 858 len = m.pos() 859 m.setpos(old_pos) 860 return len 861 862 def truncate(m): 863 m.f.truncate() 864 865 def remaining(m): 866 return m.len() - m.f.tell() 867 def eof(m): 868 return m.f.tell() == m.len() 869 870 def pos(m): 871 return m.f.tell() 872 def setpos(m, val): 873 m.f.seek(val, 0) 874 def addpos(m, val): 875 m.f.seek(val, 1) 876 def setendpos(m, val): 877 m.f.seek(val, 2) 878 879 def subpos(m, val): 880 m.addpos(-val) 881 def swappos(m, val): 882 pos = m.pos() 883 m.setpos(val) 884 return pos 885 886 def rewind(m): 887 m.setpos(0) 888 return m 889 def unwind(m): 890 m.f.seek(0, 2) 891 return m 892 893 def flush(m): 894 m.f.flush() 895 896 @property 897 def length(m): 898 return m.len() 899 @property 900 def position(m): 901 return m.pos() 902 @position.setter 903 def position(m, value): 904 m.setpos(value)
950class BinaryReader(BinaryBase): 951 """Wraps a stream, allowing to easily read binary data from it""" 952 953 def __init__(m, path, big_end = False, enc = "utf-8", wenc = "utf-16"): 954 m.big_end, m.enc, m.wenc = big_end, enc, wenc 955 956 if isinstance(path, (str, CustomPath)): 957 m.f = file_open(path) 958 else: 959 m.f = path 960 961 def u8(m): 962 return u8.struct_le.unpack(m.f.read(1))[0] 963 def u16be(m): 964 return u16.struct_be.unpack(m.f.read(2))[0] 965 def u16le(m): 966 return u16.struct_le.unpack(m.f.read(2))[0] 967 def u16(m): 968 return m.u16be() if m.big_end else m.u16le() 969 def u32be(m): 970 return u32.struct_be.unpack(m.f.read(4))[0] 971 def u32le(m): 972 return u32.struct_le.unpack(m.f.read(4))[0] 973 def u32(m): 974 return m.u32be() if m.big_end else m.u32le() 975 def u64be(m): 976 return u64.struct_be.unpack(m.f.read(8))[0] 977 def u64le(m): 978 return u64.struct_le.unpack(m.f.read(8))[0] 979 def u64(m): 980 return m.u64be() if m.big_end else m.u64le() 981 982 def s8(m): 983 return s8.struct_le.unpack(m.f.read(1))[0] 984 def s16be(m): 985 return s16.struct_be.unpack(m.f.read(2))[0] 986 def s16le(m): 987 return s16.struct_le.unpack(m.f.read(2))[0] 988 def s16(m): 989 return m.s16be() if m.big_end else m.s16le() 990 def s32be(m): 991 return s32.struct_be.unpack(m.f.read(4))[0] 992 def s32le(m): 993 return s32.struct_le.unpack(m.f.read(4))[0] 994 def s32(m): 995 return m.s32be() if m.big_end else m.s32le() 996 def s64be(m): 997 return s64.struct_be.unpack(m.f.read(8))[0] 998 def s64le(m): 999 return s64.struct_le.unpack(m.f.read(8))[0] 1000 def s64(m): 1001 return m.s64be() if m.big_end else m.s64le() 1002 1003 def bytes(m, size, allow_eof=False): 1004 result = m.f.read(size) 1005 if len(result) != size and not allow_eof: 1006 raise struct.error("end of file") 1007 return result 1008 def bytearray(m, size, allow_eof=False): 1009 result = bytearray(size) 1010 if m.f.readinto(result) != size and not allow_eof: 1011 raise struct.error("end of file") 1012 return result 1013 1014 def str(m, len, enc=None): 1015 return m.bytes(len).decode(enc or m.enc) 1016 def wstr(m, len, enc=None): 1017 return m.bytes(len * 2).decode(enc or m.wenc) 1018 1019 def f32be(m): 1020 return f32.struct_be.unpack(m.f.read(4))[0] 1021 def f32le(m): 1022 return f32.struct_le.unpack(m.f.read(4))[0] 1023 def f32(m): 1024 return m.f32be() if m.big_end else m.f32le() 1025 def f64be(m): 1026 return f64.struct_be.unpack(m.f.read(8))[0] 1027 def f64le(m): 1028 return f64.struct_le.unpack(m.f.read(8))[0] 1029 def f64(m): 1030 return m.f64be() if m.big_end else m.f64le() 1031 1032 def zbytes(m, size=None, count=1, allow_eof=False): 1033 return _read_zbytes(m.bytes, size, count, allow_eof) 1034 1035 def zstr(m, size=None, enc=None): 1036 return m.zbytes(size).decode(enc or m.enc) 1037 def wzstr(m, size=None, enc=None): 1038 return m.zbytes(size, 2).decode(enc or m.wenc) 1039 1040 def struct(m, struct): 1041 return struct.unpack(m.f.read(struct.size)) 1042 1043 def list(m, func, size): 1044 return [func() for _ in range(size)] 1045 1046 def bool(m): 1047 return m.u8() != 0 1048 1049 def nat(m): 1050 nat = 0 1051 shift = 0 1052 more = True 1053 while more: 1054 val = m.u8() 1055 nat |= (val & 0x7f) << shift 1056 more = (val >> 7) 1057 shift += 7 1058 return nat 1059 1060 def int(m): 1061 nat = m.nat() 1062 if nat & 1: 1063 return -(nat - 1) >> 1 1064 else: 1065 return nat >> 1 1066 1067 def float(m): 1068 return m.f64() # python's float 1069 1070 def nbytes(m): 1071 return m.bytes(m.nat()) 1072 1073 def align(m, size, start = 0): 1074 misalign = (m.pos() - start) % size 1075 if misalign: 1076 m.addpos(size - misalign)
Wraps a stream, allowing to easily read binary data from it
1078class BinaryBitReader(BinaryBase): 1079 """Wraps a stream, allowing to easily read bits from it""" 1080 1081 def __init__(m, f, big_end = False): 1082 m.f = f 1083 m._bits = 0 1084 m._nbits = 0 1085 m.big_end = big_end 1086 1087 @property 1088 def bit_position(m): 1089 return m.pos() * 8 - m._nbits 1090 1091 def byte_align(m): # effectively flushes 1092 m.subpos(m._nbits // 8) 1093 m._bits, m._nbits = 0, 0 1094 1095 def _add_bits_le(m, strict): 1096 value = m.f.read(1) 1097 if value: 1098 m._bits |= ord(value) << m._nbits 1099 m._nbits += 8 1100 elif strict: 1101 raise struct.error("end of file") 1102 1103 def _bits_le(m, n, advance=True): 1104 while m._nbits < n: 1105 m._add_bits_le(advance) 1106 1107 value = m._bits & ((1 << n) - 1) 1108 if advance: 1109 m._bits >>= n 1110 m._nbits -= n 1111 return value 1112 1113 def _add_bits_be(m, strict): 1114 value = m.f.read(1) 1115 if value: 1116 m._bits = (m._bits << 8) | ord(value) 1117 m._nbits += 8 1118 elif strict: 1119 raise struct.error("end of file") 1120 1121 def _bits_be(m, n, advance=True): 1122 while m._nbits < n: 1123 m._add_bits_be(advance) 1124 1125 bottom_bits = m._nbits - n 1126 value = m._bits >> bottom_bits 1127 if advance: 1128 m._bits &= (1 << bottom_bits) - 1 1129 m._nbits -= n 1130 return value 1131 1132 def bits(m, n): 1133 return m._bits_be(n) if m.big_end else m._bits_le(n) 1134 1135 def bit(m): 1136 return m.bits(1) != 0 1137 1138 def peek_bits(m, n): 1139 return m._bits_be(n, False) if m.big_end else m._bits_le(n, False) 1140 1141 def peek_bit(m): 1142 return m.peek_bits(1) != 0 1143 1144 def _advance_bits_long(m, n): 1145 n -= m._nbits 1146 m._bits, m._nbits = 0, 0 1147 m.addpos(n // 8) 1148 n %= 8 1149 if n: 1150 m._add_bits_le(True) # le/be doesn't matter after above flush 1151 return n # bits left to advance 1152 1153 def _advance_bits_le(m, n): 1154 if n > m._nbits: 1155 n = m._advance_bits_long(n) 1156 m._bits >>= n 1157 m._nbits -= n 1158 1159 def _advance_bits_be(m, n): 1160 if n > m._nbits: 1161 n = m._advance_bits_long(n) 1162 m._bits &= (1 << (m._nbits - n)) - 1 1163 m._nbits -= n 1164 1165 def advance_bits(m, n): 1166 return m._advance_bits_be(n) if m.big_end else m._advance_bits_le(n)
Wraps a stream, allowing to easily read bits from it
1168class BinaryWriter(BinaryBase): 1169 """Wraps a stream, allowing to easily write binary data to it""" 1170 1171 def __init__(m, path = None, big_end = False, enc = "utf-8", wenc = "utf-16"): 1172 m.big_end, m.enc, m.wenc = big_end, enc, wenc 1173 1174 if path is None: 1175 m.f = BytesIO() 1176 elif isinstance(path, (str, CustomPath)): 1177 m.f = file_create(path) 1178 else: 1179 m.f = path 1180 1181 def u8(m, v): 1182 m.f.write(u8.struct_le.pack(v)) 1183 def u16(m, v): 1184 if m.big_end: 1185 m.f.write(u16.struct_be.pack(v)) 1186 else: 1187 m.f.write(u16.struct_le.pack(v)) 1188 def u32(m, v): 1189 if m.big_end: 1190 m.f.write(u32.struct_be.pack(v)) 1191 else: 1192 m.f.write(u32.struct_le.pack(v)) 1193 def u64(m, v): 1194 if m.big_end: 1195 m.f.write(u64.struct_be.pack(v)) 1196 else: 1197 m.f.write(u64.struct_le.pack(v)) 1198 1199 def s8(m, v): 1200 m.f.write(s8.struct_le.pack(v)) 1201 def s16(m, v): 1202 if m.big_end: 1203 m.f.write(s16.struct_be.pack(v)) 1204 else: 1205 m.f.write(s16.struct_le.pack(v)) 1206 def s32(m, v): 1207 if m.big_end: 1208 m.f.write(s32.struct_be.pack(v)) 1209 else: 1210 m.f.write(s32.struct_le.pack(v)) 1211 def s64(m, v): 1212 if m.big_end: 1213 m.f.write(s64.struct_be.pack(v)) 1214 else: 1215 m.f.write(s64.struct_le.pack(v)) 1216 1217 def f32(m, v): 1218 if m.big_end: 1219 m.f.write(f32.struct_be.pack(v)) 1220 else: 1221 m.f.write(f32.struct_le.pack(v)) 1222 def f64(m, v): 1223 if m.big_end: 1224 m.f.write(f64.struct_be.pack(v)) 1225 else: 1226 m.f.write(f64.struct_le.pack(v)) 1227 1228 def bytes(m, v): 1229 m.f.write(v) 1230 1231 def str(m, v, enc=None): 1232 m.bytes(v.encode(enc or m.enc)) 1233 def wstr(m, v, enc=None): 1234 m.bytes(v.encode(enc or m.wenc)) 1235 1236 def zbytes(m, v, size=None, count=1): 1237 _write_zbytes(m.bytes, v, size, count) 1238 1239 def zstr(m, v, size=None, enc=None): 1240 m.zbytes(v.encode(enc or m.enc), size) 1241 def wzstr(m, v, size=None, enc=None): 1242 m.zbytes(v.encode(enc or m.wenc), size, 2) 1243 1244 def struct(m, struct, value): 1245 m.f.write(struct.pack(*value)) 1246 1247 def list(m, func, value): 1248 for v in value: 1249 func(v) 1250 1251 def fill(m, v, size): 1252 for i in range(size): 1253 m.u8(v) 1254 1255 def nat(m, v): 1256 assert v >= 0 1257 more = True 1258 while more: 1259 part = v & 0x7f 1260 v >>= 7 1261 more = v != 0 1262 m.u8(part | (more << 7)) 1263 1264 def bool(m, v): 1265 m.u8(1 if v else 0) 1266 1267 def int(m, v): 1268 if v >= 0: 1269 m.nat(v << 1) 1270 else: 1271 m.nat((-v << 1) + 1) 1272 1273 def float(m, v): 1274 m.f64(v) # python's float 1275 1276 def nbytes(m, v): 1277 m.nat(len(v)) 1278 m.bytes(v) 1279 1280 def align(m, size, start = 0, value = 0): 1281 misalign = (m.pos() - start) % size 1282 if misalign: 1283 for _ in range(size - misalign): 1284 m.u8(value)
Wraps a stream, allowing to easily write binary data to it
1286class BinaryBitWriter(BinaryBase): 1287 """Wraps a stream, allowing to easily write bits to it""" 1288 1289 def __init__(m, f, big_end = False): 1290 m.f = f 1291 m._bits = 0 1292 m._nbits = 0 1293 m.big_end = big_end 1294 1295 @property 1296 def bit_position(m): 1297 return m.pos() * 8 - m._nbits 1298 1299 def byte_align(m): 1300 m.flush() 1301 1302 def _remove_bits_le(m): 1303 m.f.write(byte(m._bits & 0xff)) 1304 m._bits >>= 8 1305 m._nbits -= 8 1306 1307 def _bits_le(m, n, v): 1308 m._bits |= v << m._nbits 1309 m._nbits += n 1310 1311 while m._nbits >= 8: 1312 m._remove_bits_le() 1313 1314 def _remove_bits_be(m): 1315 m._nbits -= 8 1316 m.f.write(byte(m._bits >> m._nbits)) 1317 m._bits &= (1 << m._nbits) - 1 1318 1319 def _bits_be(m, n, v): 1320 m._bits = (m._bits << n) | v 1321 m._nbits += n 1322 1323 while m._nbits >= 8: 1324 m._remove_bits_be() 1325 1326 def bits(m, n, v): 1327 if m.big_end: 1328 m._bits_be(n, v) 1329 else: 1330 m._bits_le(n, v) 1331 1332 def bit(m, v): 1333 m.bits(1, v) 1334 1335 def close(m): 1336 m.flush() 1337 super().close() 1338 1339 def _flush_le(m): 1340 if m._nbits: 1341 m.f.write(byte(m._bits & 0xff)) 1342 m._bits, m._nbits = 0, 0 1343 1344 def _flush_be(m): 1345 if m._nbits: 1346 m.f.write(byte(m._bits << (8 - m._nbits))) 1347 m._bits, m._nbits = 0, 0 1348 1349 def flush(m): 1350 if m.big_end: 1351 m._flush_be() 1352 else: 1353 m._flush_le()
Wraps a stream, allowing to easily write bits to it
1355class BinaryBuffer: 1356 """Wraps a bytearray, allowing to easily read & write binary data in it""" 1357 # TODO: make more consistent with BinaryReader/Writer (big_end, enc, wenc) 1358 1359 def __init__(m, src): 1360 if isinstance(src, bytearray): 1361 m.buf = src 1362 else: 1363 m.buf = bytearray(src) 1364 1365 def __len__(m): 1366 return len(m.buf) 1367 1368 def r_u8(m, addr): 1369 return m.buf[addr] 1370 def w_u8(m, addr, val): 1371 m.buf[addr] = val 1372 1373 def r_u16(m, addr): 1374 return u16.struct_le.unpack_from(m.buf, addr)[0] 1375 def w_u16(m, addr, val): 1376 u16.struct_le.pack_into(m.buf, addr, val) 1377 1378 def r_u32(m, addr): 1379 return u32.struct_le.unpack_from(m.buf, addr)[0] 1380 def w_u32(m, addr, val): 1381 u32.struct_le.pack_into(m.buf, addr, val) 1382 1383 def r_u64(m, addr): 1384 return u64.struct_le.unpack_from(m.buf, addr)[0] 1385 def w_u64(m, addr, val): 1386 u64.struct_le.pack_into(m.buf, addr, val) 1387 1388 def r_s8(m, addr): 1389 return s8.struct_le.unpack_from(m.buf, addr)[0] 1390 def w_s8(m, addr, val): 1391 s8.struct_le.pack_into(m.buf, addr, val) 1392 1393 def r_s16(m, addr): 1394 return s16.struct_le.unpack_from(m.buf, addr)[0] 1395 def w_s16(m, addr, val): 1396 s16.struct_le.pack_into(m.buf, addr, val) 1397 1398 def r_s32(m, addr): 1399 return s32.struct_le.unpack_from(m.buf, addr)[0] 1400 def w_s32(m, addr, val): 1401 s32.struct_le.pack_into(m.buf, addr, val) 1402 1403 def r_s64(m, addr): 1404 return s64.struct_le.unpack_from(m.buf, addr)[0] 1405 def w_s64(m, addr, val): 1406 s64.struct_le.pack_into(m.buf, addr, val) 1407 1408 def r_f32(m, addr): 1409 return f32.struct_le.unpack_from(m.buf, addr)[0] 1410 def w_f32(m, addr, val): 1411 f32.struct_le.pack_into(m.buf, addr, val) 1412 1413 def r_f64(m, addr): 1414 return f64.struct_le.unpack_from(m.buf, addr)[0] 1415 def w_f64(m, addr, val): 1416 f64.struct_le.pack_into(m.buf, addr, val) 1417 1418 def r_bytes(m, addr, count, allow_eof=False): 1419 data = m.buf[addr:addr+count] 1420 if not allow_eof and len(data) < count: 1421 raise struct.error("end of buffer") 1422 return data 1423 1424 def r_zbytes(m, addr, size=None, count = 1, allow_eof=False): 1425 def bytes(count, allow_eof): 1426 nonlocal addr 1427 value = m.r_bytes(addr, count, allow_eof) 1428 addr += len(value) 1429 return value 1430 1431 return _read_zbytes(bytes, size, count, allow_eof) 1432 1433 def r_zstr(m, addr, size=None, enc="utf-8"): 1434 return m.r_zbytes(addr, size).decode(enc) 1435 def r_wzstr(m, addr, size=None, enc="utf-16"): 1436 return m.r_zbytes(addr, size, 2).decode(enc) 1437 1438 def w_bytes(m, addr, val): 1439 m.buf[addr:addr+len(val)] = val 1440 1441 def w_zbytes(m, addr, val, size=None, count=1): 1442 def bytes(val): 1443 nonlocal addr 1444 m.w_bytes(addr, val) 1445 addr += len(val) 1446 1447 _write_zbytes(bytes, val, size, count) 1448 1449 def w_zstr(m, addr, val, size=None, enc="utf-8"): 1450 m.w_zbytes(addr, val.encode(enc), size) 1451 def w_wzstr(m, addr, val, size=None, enc='utf-16'): 1452 m.w_zbytes(addr, val.encode(enc), size, 2) 1453 1454 def r_struct(m, addr, struct): 1455 return struct.unpack_from(m.buf, addr) 1456 def w_struct(m, addr, struct, val): 1457 struct.pack_into(m.buf, addr, *val) 1458 1459 def w_from(m, addr, src, src_addr, count): 1460 m.buf[addr:addr+count] = src.r_bytes(src_addr, count) 1461 def w_fill(m, addr, value, count): 1462 m.buf[addr:addr+count] = byte(value) * count 1463 def w_zero(m, addr, count): 1464 m.w_fill(addr, 0, count)
Wraps a bytearray, allowing to easily read & write binary data in it
1466def e(value): 1467 """Return if 'value' is not None (for my sanity and others' insanity)""" 1468 return value is not None
Return if 'value' is not None (for my sanity and others' insanity)
1470def default(value, defval): 1471 """Return 'defval' if 'value' is None""" 1472 return value if value != None else defval
Return 'defval' if 'value' is None
The identity function
1478def product(items): 1479 """Return the product of 'items'""" 1480 result = 1 1481 for item in items: 1482 result *= item 1483 return result
Return the product of 'items'
1485def str_insert(str, at, what): 1486 """Return a string based on 'str' with 'what' inserted at position 'at'""" 1487 return str[:at] + what + str[at:]
Return a string based on 'str' with 'what' inserted at position 'at'
1489def str_replace_at(str, at, count, what): 1490 """Return a string based on 'str' with 'what' replacing 'count' chars at position 'at'""" 1491 return str[:at] + what + str[at + count:]
Return a string based on 'str' with 'what' replacing 'count' chars at position 'at'
1493def str_replace_between(str, start, end, what): 1494 """Return a string based on 'str' with 'what' replacing chars between 'start' and 'end'""" 1495 return str[:start] + what + str[end:]
Return a string based on 'str' with 'what' replacing chars between 'start' and 'end'
1497def str_remove_at(str, at, count): 1498 """Return a string based on 'str' with 'count' chars removed at position 'at'""" 1499 return str[:at] + str[at + count:]
Return a string based on 'str' with 'count' chars removed at position 'at'
1501def str_remove_between(str, start, end): 1502 """Return a string based on 'str' with chars removed between 'start' and 'end""" 1503 return str[:start] + str[end:]
Return a string based on 'str' with chars removed between 'start' and 'end
1505def str_trunc(str, count): 1506 """Truncates a string if larger than 'count' characters""" 1507 if len(str) > count: 1508 return str[:count] 1509 else: 1510 return str
Truncates a string if larger than 'count' characters
1512def str_ljust_trunc(str, count, fillchar = ' '): 1513 """Left-justifies a string and truncates it""" 1514 return str_trunc(str, count).ljust(count, fillchar)
Left-justifies a string and truncates it
1516def str_rjust_trunc(str, count, fillchar = ' '): 1517 """Right-justifies a string and truncates it""" 1518 return str_trunc(str, count).rjust(count, fillchar)
Right-justifies a string and truncates it
1520def str_remove_prefix(str, prefix): 1521 """Return a string based on 'str' with 'prefix' removed from its beginning""" 1522 if str.startswith(prefix): 1523 return str[len(prefix):] 1524 else: 1525 return str
Return a string based on 'str' with 'prefix' removed from its beginning
1527def str_remove_suffix(str, suffix): 1528 """Return a string based on 'str' with 'suffix' removed from its end""" 1529 if str.endswith(suffix): 1530 return str[:-len(suffix)] 1531 else: 1532 return str
Return a string based on 'str' with 'suffix' removed from its end
1534def str_before_first(str, match, s=None, e=None): 1535 """Return 'str' before the first 'match'""" 1536 i = str.find(match, s, e) 1537 return str[s:i] if i >= 0 else str[s:e]
Return 'str' before the first 'match'
1539def str_before_last(str, match, s=None, e=None): 1540 """Return 'str' before the last 'match'""" 1541 i = str.rfind(match, s, e) 1542 return str[s:i] if i >= 0 else ""
Return 'str' before the last 'match'
1544def str_after_first(str, match, s=None, e=None): 1545 """Return 'str' after the first 'match'""" 1546 i = str.find(match, s, e) 1547 return str[i+len(match):e] if i >= 0 else ""
Return 'str' after the first 'match'
1549def str_after_last(str, match, s=None, e=None): 1550 """Return 'str' after the last 'match'""" 1551 i = str.rfind(match, s, e) 1552 return str[i+len(match):e] if i >= 0 else str[s:e]
Return 'str' after the last 'match'
1554def str_split_first(str, match, s=None, e=None): 1555 """Return 'str' before and after the first 'match'""" 1556 i = str.find(match, s, e) 1557 return (str[s:i], str[i+len(match):e]) if i >= 0 else (str[s:e], "")
Return 'str' before and after the first 'match'
1559def str_split_last(str, match, s=None, e=None): 1560 """Return 'str' before and after the last 'match'""" 1561 i = str.rfind(match, s, e) 1562 return (str[s:i], str[i+len(match):e]) if i >= 0 else ("", str[s:e])
Return 'str' before and after the last 'match'
1564def str_replace_batch(val, batch): 1565 """Return a string based on 'val' that contains replacements defined in 'batch'. 1566 'batch' is a dict or list of pairs, with each pair being: 1567 (str, str or (lambda: str)) - simple replacement 1568 (regex, str) - regex replacement (with regex pre-compilation) 1569 ((re, str), str) - regex replacement without pre-compilation""" 1570 if isinstance(batch, dict): 1571 batch = batch.items() 1572 1573 for k, v in batch: 1574 if isinstance(k, str): 1575 if callable(v): 1576 if k not in val: 1577 continue 1578 v = v() 1579 val = val.replace(k, v) 1580 elif isinstance(k, re.Pattern): 1581 val = k.sub(v, val) 1582 else: 1583 assert k[0] == re 1584 val = re.sub(k[1], v, val) 1585 return val
Return a string based on 'val' that contains replacements defined in 'batch'. 'batch' is a dict or list of pairs, with each pair being: (str, str or (lambda: str)) - simple replacement (regex, str) - regex replacement (with regex pre-compilation) ((re, str), str) - regex replacement without pre-compilation
1564def str_replace_batch(val, batch): 1565 """Return a string based on 'val' that contains replacements defined in 'batch'. 1566 'batch' is a dict or list of pairs, with each pair being: 1567 (str, str or (lambda: str)) - simple replacement 1568 (regex, str) - regex replacement (with regex pre-compilation) 1569 ((re, str), str) - regex replacement without pre-compilation""" 1570 if isinstance(batch, dict): 1571 batch = batch.items() 1572 1573 for k, v in batch: 1574 if isinstance(k, str): 1575 if callable(v): 1576 if k not in val: 1577 continue 1578 v = v() 1579 val = val.replace(k, v) 1580 elif isinstance(k, re.Pattern): 1581 val = k.sub(v, val) 1582 else: 1583 assert k[0] == re 1584 val = re.sub(k[1], v, val) 1585 return val
Return a string based on 'val' that contains replacements defined in 'batch'. 'batch' is a dict or list of pairs, with each pair being: (str, str or (lambda: str)) - simple replacement (regex, str) - regex replacement (with regex pre-compilation) ((re, str), str) - regex replacement without pre-compilation
1589def list_chunk(list, size): 1590 """Split a list into sublists of size 'size' each (except possibly the last sublist)""" 1591 count = div_up(len(list), size) 1592 return [list[i * size : (i + 1) * size] for i in range(count)]
Split a list into sublists of size 'size' each (except possibly the last sublist)
1594def list_remove(list, func): 1595 """Remove elements from a list that match the given 'func'""" 1596 for i, item in enumerate(list): 1597 if func(item): 1598 del list[i] 1599 i -= 1
Remove elements from a list that match the given 'func'
1601def list_find(list, val): 1602 """Find the index of the given element in the list""" 1603 try: 1604 return list.index(val) 1605 except ValueError: 1606 return -1
Find the index of the given element in the list
1608def list_find_where(list, func): 1609 """Find the index of the first element in a list that matches predicate 'func'""" 1610 for i, item in enumerate(list): 1611 if func(item): 1612 return i 1613 return -1
Find the index of the first element in a list that matches predicate 'func'
1615def list_rfind_where(list, func): 1616 """Find the index of the last element in a list that matches predicate 'func'""" 1617 for i_rev, item in enumerate(reversed(list)): 1618 if func(item): 1619 return len(list) - 1 - i_rev 1620 return -1
Find the index of the last element in a list that matches predicate 'func'
1622def list_get(list, i, defval = None): 1623 """Get the 'i'th element in the list, or 'defval' (default: None) if not a valid index""" 1624 return list[i] if 0 <= i < len(list) else defval
Get the 'i'th element in the list, or 'defval' (default: None) if not a valid index
1626def list_rget(list, i, defval = None): 1627 """Get the 'i'th element in the list from the end, or 'defval' (default: None) if not a valid index""" 1628 return list[-(i+1)] if 0 <= i < len(list) else defval
Get the 'i'th element in the list from the end, or 'defval' (default: None) if not a valid index
1630def list_set(list, i, val, defval = None): 1631 """Set the 'i'th element in the list, growing the list with 'defval's (default: Nones) as needed""" 1632 assert i >= 0 1633 while i >= len(list): 1634 list.append(defval) 1635 list[i] = val
Set the 'i'th element in the list, growing the list with 'defval's (default: Nones) as needed
1622def list_get(list, i, defval = None): 1623 """Get the 'i'th element in the list, or 'defval' (default: None) if not a valid index""" 1624 return list[i] if 0 <= i < len(list) else defval
Get the 'i'th element in the list, or 'defval' (default: None) if not a valid index
1626def list_rget(list, i, defval = None): 1627 """Get the 'i'th element in the list from the end, or 'defval' (default: None) if not a valid index""" 1628 return list[-(i+1)] if 0 <= i < len(list) else defval
Get the 'i'th element in the list from the end, or 'defval' (default: None) if not a valid index
1589def list_chunk(list, size): 1590 """Split a list into sublists of size 'size' each (except possibly the last sublist)""" 1591 count = div_up(len(list), size) 1592 return [list[i * size : (i + 1) * size] for i in range(count)]
Split a list into sublists of size 'size' each (except possibly the last sublist)
1641def list_pop(list, defval = None): 1642 """Pop the element from the list, or get 'defval' (default: None) if empty""" 1643 return list.pop() if list else defval
Pop the element from the list, or get 'defval' (default: None) if empty
1645def list_unpack(list, n, defval = None): 1646 """Return the 'n' first elements in the list, padding with 'defval' if needed""" 1647 for i in range(n): 1648 yield list_get(list, i, defval)
Return the 'n' first elements in the list, padding with 'defval' if needed
1650def tuple_insert(tuple, i, newval): 1651 """Return a new tuple based on 'tuple' with 'newval' inserted at index 'i'""" 1652 return tuple[:i] + (newval,) + tuple[i:]
Return a new tuple based on 'tuple' with 'newval' inserted at index 'i'
1654def tuple_replace_at(tuple, i, newval): 1655 """Return a new tuple based on 'tuple' with 'newval' replacing the element at index 'i'""" 1656 return tuple[:i] + (newval,) + tuple[i+1:]
Return a new tuple based on 'tuple' with 'newval' replacing the element at index 'i'
1658def tuple_remove_at(tuple, i, count=1): 1659 """Return a new tuple based on 'tuple' with 'count' elements removed at index 'i'""" 1660 return tuple[:i] + tuple[i+count:]
Return a new tuple based on 'tuple' with 'count' elements removed at index 'i'
1674def func_union(func1, func2, return_early=None, return_combine=None): 1675 """Return a function that behaves like func1 followed by func2. Either of func1/func2 may be None. 1676 'return_early' can decide whether to return func1's result. 'return_combine' can combine func1's and func2's results""" 1677 if func1 is None: 1678 return func2 1679 elif func2 is None: 1680 return func1 1681 elif return_early: 1682 def union(*args, **kwargs): 1683 ret = func1(*args, **kwargs) 1684 if return_early(ret): 1685 return ret 1686 return func2(*args, **kwargs) 1687 return union 1688 else: 1689 def union(*args, **kwargs): 1690 ret1 = func1(*args, **kwargs) 1691 ret2 = func2(*args, **kwargs) 1692 if return_combine: 1693 return return_combine(ret1, ret2) 1694 return None 1695 return union
Return a function that behaves like func1 followed by func2. Either of func1/func2 may be None. 'return_early' can decide whether to return func1's result. 'return_combine' can combine func1's and func2's results
1697def getattrs(obj, private = True, magic = False): 1698 """Get all attributes of 'obj' (By default, including _privates but excluding __magic__)""" 1699 for attr in dir(obj): 1700 if not private and attr.startswith("_"): 1701 continue 1702 if not magic and attr.startswith("__") and attr.endswith("__"): 1703 continue 1704 yield attr, getattr(obj, attr)
Get all attributes of 'obj' (By default, including _privates but excluding __magic__)
1706class Point(Tuple): 1707 """An (x,y) tuple representing a 2d point and supporting arithmetic operations""" 1708 x = y = ... 1709 1710 def __add__(m, other): 1711 assert isinstance(other, Point) 1712 return Point(m.x + other.x, m.y + other.y) 1713 1714 def __sub__(m, other): 1715 assert isinstance(other, Point) 1716 return Point(m.x - other.x, m.y - other.y) 1717 1718 def __mul__(m, other): 1719 if isinstance(other, Point): 1720 return Point(m.x * other.x, m.y * other.y) 1721 else: 1722 return Point(m.x * other, m.y * other) 1723 1724 def __rmul__(m, other): 1725 return Point(other * m.x, other * m.y) 1726 1727 def __truediv__(m, other): 1728 if isinstance(other, Point): 1729 return Point(m.x / other.x, m.y / other.y) 1730 else: 1731 return Point(m.x / other, m.y / other) 1732 1733 def __rtruediv__(m, other): 1734 return Point(other / m.x, other / m.y) 1735 1736 __div__ = __truediv__ 1737 __rdiv__ = __rtruediv__ 1738 1739 def __floordiv__(m, other): 1740 if isinstance(other, Point): 1741 return Point(m.x // other.x, m.y // other.y) 1742 else: 1743 return Point(m.x // other, m.y // other) 1744 1745 def __rfloordiv__(m, other): 1746 return Point(other // m.x, other // m.y) 1747 1748 def __mod__(m, other): 1749 if isinstance(other, Point): 1750 return Point(m.x % other.x, m.y % other.y) 1751 else: 1752 return Point(m.x % other, m.y % other) 1753 1754 def __rmod__(m, other): 1755 return Point(other % m.x, other % m.y) 1756 1757 def __abs__(m): 1758 return Point(abs(m.x), abs(m.y)) 1759 1760 def __neg__(m): 1761 return Point(-m.x, -m.y) 1762 1763 def __bool__(m): 1764 return m.x or m.y 1765 1766 def __ge__(m, other): 1767 assert isinstance(other, Point) 1768 return m.x >= other.x and m.y >= other.y 1769 1770 def __gt__(m, other): 1771 assert isinstance(other, Point) 1772 return m.x > other.x and m.y > other.y 1773 1774 def __le__(m, other): 1775 assert isinstance(other, Point) 1776 return m.x <= other.x and m.y <= other.y 1777 1778 def __lt__(m, other): 1779 assert isinstance(other, Point) 1780 return m.x < other.x and m.y < other.y 1781 1782 def set_x(m, x): 1783 return Point(x, m.y) 1784 1785 def set_y(m, y): 1786 return Point(m.x, y) 1787 1788 def int(m): 1789 return Point(int(m.x), int(m.y)) 1790 1791 def float(m): 1792 return Point(float(m.x), float(m.y)) 1793 1794 @classmethod 1795 def repeat(cls, value): 1796 return cls(value, value) 1797 1798 @property 1799 def norm_squared(m): 1800 return m.x * m.x + m.y * m.y 1801 1802 @property 1803 def norm(m): 1804 return math.sqrt(m.norm_squared) 1805 1806 @staticmethod 1807 def distance_squared(m, o): 1808 return (m - o).norm_squared 1809 1810 @staticmethod 1811 def distance(m, o): 1812 return (m - o).norm
An (x,y) tuple representing a 2d point and supporting arithmetic operations
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
1816class Rect(Tuple): 1817 """An (x,y,w,h) tuple representing a 2d rectangle""" 1818 x = y = w = h = ... 1819 1820 @property 1821 def x2(m): 1822 return m.x + m.w 1823 1824 @property 1825 def y2(m): 1826 return m.y + m.h 1827 1828 @property 1829 def pos(m): 1830 return Point(m.x, m.y) 1831 1832 @property 1833 def size(m): 1834 return Point(m.w, m.h) 1835 1836 @property 1837 def pos2(m): 1838 return Point(m.x2, m.y2) 1839 1840 @property 1841 def center(m): 1842 return m.pos + m.size / 2 1843 1844 def __bool__(m): 1845 return m.w > 0 and m.h > 0 1846 1847 def __contains__(m, p): 1848 if isinstance(p, Point): 1849 return p >= m.pos and p < m.pos2 1850 elif isinstance(p, Rect): 1851 return p.pos >= m.pos and p.pos2 <= m.pos2 1852 else: 1853 raise Exception("Not implemented") 1854 1855 def overlaps(m, p): 1856 assert isinstance(p, Rect) 1857 return p.pos < m.pos2 and p.pos2 > m.pos 1858 1859 def __and__(m, p): 1860 assert isinstance(p, Rect) 1861 return Rect.from_coords(max(m.x, p.x), max(m.y, p.y), max(min(m.x2, p.x2), 0), max(min(m.y2, p.y2), 0)) 1862 1863 def __add__(m, other): 1864 assert isinstance(other, Point) 1865 return Rect(m.x + other.x, m.y + other.y, m.w, m.h) 1866 1867 def __sub__(m, other): 1868 assert isinstance(other, Point) 1869 return Rect(m.x - other.x, m.y - other.y, m.w, m.h) 1870 1871 @classmethod 1872 def from_pos_size(cls, pos, size): 1873 return cls(pos.x, pos.y, size.x, size.y) 1874 1875 @classmethod 1876 def from_pos(cls, pos, pos2): 1877 return cls(pos.x, pos.y, pos2.x - pos.x, pos2.y - pos.y) 1878 1879 @classmethod 1880 def from_coords(cls, x, y, x2, y2): 1881 return cls(x, y, x2 - x, y2 - y)
An (x,y,w,h) tuple representing a 2d rectangle
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
1885class ProjectedDictBase(dict): 1886 """A dict baseclass where keys are projected via _project before compared""" 1887 @classmethod 1888 def _project(cls, key): 1889 raise NotImplementedError() 1890 1891 def __init__(m, E=None, **F): 1892 super().__init__() 1893 m.update(E, **F) 1894 def __getitem__(m, key): 1895 return super().__getitem__(m.__class__._project(key)) 1896 def __setitem__(m, key, value): 1897 super().__setitem__(m.__class__._project(key), value) 1898 def __delitem__(m, key): 1899 return super().__delitem__(m.__class__._project(key)) 1900 def __contains__(m, key): 1901 return super().__contains__(m.__class__._project(key)) 1902 def pop(m, key, *args, **kwargs): 1903 return super().pop(m.__class__._project(key), *args, **kwargs) 1904 def get(m, key, *args, **kwargs): 1905 return super().get(m.__class__._project(key), *args, **kwargs) 1906 def setdefault(m, key, *args, **kwargs): 1907 return super().setdefault(m.__class__._project(key), *args, **kwargs) 1908 1909 def update(m, E=None, **F): 1910 if E: 1911 if hasattr(E, "items"): 1912 for k, v in E.items(): 1913 m[k] = v 1914 else: 1915 for k, v in E: 1916 m[k] = v 1917 1918 if F: 1919 for k, v in F.items(): 1920 m[k] = v
A dict baseclass where keys are projected via _project before compared
1902 def pop(m, key, *args, **kwargs): 1903 return super().pop(m.__class__._project(key), *args, **kwargs)
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If the key is not found, return the default if given; otherwise, raise a KeyError.
1904 def get(m, key, *args, **kwargs): 1905 return super().get(m.__class__._project(key), *args, **kwargs)
Return the value for key if key is in the dictionary, else default.
1906 def setdefault(m, key, *args, **kwargs): 1907 return super().setdefault(m.__class__._project(key), *args, **kwargs)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
1909 def update(m, E=None, **F): 1910 if E: 1911 if hasattr(E, "items"): 1912 for k, v in E.items(): 1913 m[k] = v 1914 else: 1915 for k, v in E: 1916 m[k] = v 1917 1918 if F: 1919 for k, v in F.items(): 1920 m[k] = v
D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
1922class CaseInsensitiveDict(ProjectedDictBase): 1923 """A dict where key comparison is case-insensitive""" 1924 @classmethod 1925 def _project(cls, key): 1926 return key.lower()
A dict where key comparison is case-insensitive
Inherited Members
1928class defaultlist(list): 1929 """A list allowing read/write of arbitrary indices, filling unused indices via 'defgetter'()""" 1930 def __init__(m, defgetter): 1931 m.defgetter = defgetter 1932 1933 def _fill(m, i): 1934 if isinstance(i, slice): 1935 while i.stop > len(m): 1936 m.append(m.defgetter()) 1937 else: 1938 while i >= len(m): 1939 m.append(m.defgetter()) 1940 1941 def __getitem__(m, i): 1942 m._fill(i) 1943 return list.__getitem__(m, i) 1944 1945 def __setitem__(m, i, val): 1946 m._fill(i) 1947 list.__setitem__(m, i, val)
A list allowing read/write of arbitrary indices, filling unused indices via 'defgetter'()
1949class MultidimArray(object): 1950 """A multi-dimensional array of a fixed size""" 1951 def __init__(m, size, defval=None): 1952 m.dim = len(size) 1953 m.size = size 1954 m.array = [defval] * product(size) 1955 1956 def copy(m): 1957 return deepcopy(m) 1958 1959 def _getindex(m, indices): 1960 array_index = 0 1961 for i in range(m.dim): 1962 index, size = indices[i], m.size[i] 1963 if not (0 <= index < size): 1964 raise IndexError(indices) 1965 if i > 0: 1966 array_index *= size 1967 array_index += index 1968 return array_index 1969 1970 def __getitem__(m, indices): 1971 return m.array[m._getindex(indices)] 1972 1973 def __setitem__(m, indices, value): 1974 m.array[m._getindex(indices)] = value 1975 1976 def indices(m): 1977 indices = [0] * m.dim 1978 while True: 1979 yield indices 1980 1981 for i in reversed(range(m.dim)): 1982 indices[i] += 1 1983 if indices[i] >= m.size[i]: 1984 indices[i] = 0 1985 else: 1986 break 1987 else: 1988 break
A multi-dimensional array of a fixed size
1990class HeapQueue: 1991 """A class wrapper over heapq""" 1992 def __init__(m, iterable=None): 1993 m.list = list(iterable) if e(iterable) else [] 1994 heapq.heapify(m.list) 1995 1996 def add(m, v): 1997 heapq.heappush(m.list, v) 1998 1999 def peekleft(m): 2000 return m.list[0] 2001 2002 def popleft(m): 2003 return heapq.heappop(m.list) 2004 2005 def __len__(m): 2006 return len(m.list) 2007 2008 def __repr__(m): 2009 return f"HeapQueue({repr(m.list)})"
A class wrapper over heapq
2011class RangeSet: 2012 """A set of non-empty non-overlapping/touching ranges (tuples of (start,stop))""" 2013 def __init__(m, ranges=None): 2014 m.list = [] 2015 for range in ranges or (): 2016 m.add(range) 2017 2018 def add(m, v): 2019 v_start, v_stop = v 2020 if v_start >= v_stop: 2021 return 2022 i_start = i_end = bisect.bisect_right(m.list, (v_start, math.inf)) 2023 2024 if i_start > 0: 2025 prev_start, prev_stop = m.list[i_start - 1] # prev_start <= v_start 2026 if prev_stop >= v_start: 2027 if prev_stop >= v_stop: 2028 return 2029 i_start -= 1 2030 v = (v_start := prev_start, v_stop) 2031 2032 while i_end < len(m.list): 2033 next_start, next_stop = m.list[i_end] # next_start > v_start 2034 if next_start > v_stop: 2035 break 2036 i_end += 1 2037 if next_stop > v_stop: 2038 v = (v_start, v_stop := next_stop) 2039 break 2040 2041 if not isinstance(v, tuple): 2042 v = (v_start, v_stop) 2043 m.list[i_start:i_end] = (v,) 2044 2045 def remove(m, v): 2046 v_start, v_stop = v 2047 if v_start >= v_stop: 2048 return 2049 i_start = i_end = bisect.bisect_left(m.list, (v_start, -math.inf)) 2050 repls = () 2051 2052 if i_start > 0: 2053 prev_start, prev_stop = m.list[i_start - 1] # prev_start < v_start 2054 if prev_stop > v_start: 2055 i_start -= 1 2056 repls = (*repls, (prev_start, v_start)) 2057 if prev_stop > v_stop: 2058 repls = (*repls, (v_stop, prev_stop)) 2059 2060 while i_end < len(m.list): 2061 next_start, next_stop = m.list[i_end] # next_start >= v_start 2062 if next_start >= v_stop: 2063 break 2064 i_end += 1 2065 if next_stop > v_stop: 2066 repls = (*repls, (v_stop, next_stop)) 2067 break 2068 2069 if i_end != i_start: 2070 m.list[i_start:i_end] = repls 2071 2072 def __iadd__(m, o): 2073 for v in o: 2074 m.add(v) 2075 __ior__ = __iadd__ 2076 def __isub__(m, o): 2077 for v in o: 2078 m.remove(v) 2079 2080 def __bool__(m): 2081 return bool(m.list) 2082 # __len__ - len or sum-lens? 2083 def __iter__(m): 2084 return iter(m.list) 2085 2086 def __repr__(m): 2087 return f"RangeSet({repr(m.list)})"
A set of non-empty non-overlapping/touching ranges (tuples of (start,stop))
2018 def add(m, v): 2019 v_start, v_stop = v 2020 if v_start >= v_stop: 2021 return 2022 i_start = i_end = bisect.bisect_right(m.list, (v_start, math.inf)) 2023 2024 if i_start > 0: 2025 prev_start, prev_stop = m.list[i_start - 1] # prev_start <= v_start 2026 if prev_stop >= v_start: 2027 if prev_stop >= v_stop: 2028 return 2029 i_start -= 1 2030 v = (v_start := prev_start, v_stop) 2031 2032 while i_end < len(m.list): 2033 next_start, next_stop = m.list[i_end] # next_start > v_start 2034 if next_start > v_stop: 2035 break 2036 i_end += 1 2037 if next_stop > v_stop: 2038 v = (v_start, v_stop := next_stop) 2039 break 2040 2041 if not isinstance(v, tuple): 2042 v = (v_start, v_stop) 2043 m.list[i_start:i_end] = (v,)
2045 def remove(m, v): 2046 v_start, v_stop = v 2047 if v_start >= v_stop: 2048 return 2049 i_start = i_end = bisect.bisect_left(m.list, (v_start, -math.inf)) 2050 repls = () 2051 2052 if i_start > 0: 2053 prev_start, prev_stop = m.list[i_start - 1] # prev_start < v_start 2054 if prev_stop > v_start: 2055 i_start -= 1 2056 repls = (*repls, (prev_start, v_start)) 2057 if prev_stop > v_stop: 2058 repls = (*repls, (v_stop, prev_stop)) 2059 2060 while i_end < len(m.list): 2061 next_start, next_stop = m.list[i_end] # next_start >= v_start 2062 if next_start >= v_stop: 2063 break 2064 i_end += 1 2065 if next_stop > v_stop: 2066 repls = (*repls, (v_stop, next_stop)) 2067 break 2068 2069 if i_end != i_start: 2070 m.list[i_start:i_end] = repls
2089class RawIOBaseWSeek(io.RawIOBase): 2090 """Like RawIOBase, but allows seeking""" 2091 def seek(m, position, whence=io.SEEK_SET): 2092 if whence == io.SEEK_SET: 2093 m.position = position 2094 elif whence == io.SEEK_CUR: 2095 m.position += position 2096 elif whence == io.SEEK_END: 2097 m.position = m.length + position 2098 return m.position
Like RawIOBase, but allows seeking
2091 def seek(m, position, whence=io.SEEK_SET): 2092 if whence == io.SEEK_SET: 2093 m.position = position 2094 elif whence == io.SEEK_CUR: 2095 m.position += position 2096 elif whence == io.SEEK_END: 2097 m.position = m.length + position 2098 return m.position
Change the stream position to the given byte offset.
offset The stream position, relative to 'whence'. whence The relative position to seek from.
The offset is interpreted relative to the position indicated by whence. Values for whence are:
- os.SEEK_SET or 0 -- start of stream (the default); offset should be zero or positive
- os.SEEK_CUR or 1 -- current stream position; offset may be negative
- os.SEEK_END or 2 -- end of stream; offset is usually negative
Return the new absolute position.
2100class PartialIO(RawIOBaseWSeek): 2101 """Exposes a region of an existing stream as a stream""" 2102 def __init__(m, io, offset, length=None): 2103 length = length if e(length) else io.length - offset 2104 m.io = io 2105 m.position = 0 2106 m.offset = offset 2107 m.length = length 2108 2109 def flush(m): 2110 return m.io.flush() 2111 2112 def readinto(m, target): 2113 size = len(target) 2114 view = memoryview(target) 2115 2116 size = max(min(size, m.length - m.position), 0) 2117 m.io.seek(m.offset + m.position) 2118 count = m.io.readinto(view[:size]) 2119 2120 m.position += count 2121 return count 2122 2123 def write(m, data): 2124 size = len(data) 2125 view = memoryview(data) 2126 2127 size = max(min(size, m.length - m.position), 0) 2128 m.io.seek(m.offset + m.position) 2129 count = m.io.write(view[:size]) 2130 2131 m.position += count 2132 return count
Exposes a region of an existing stream as a stream
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
Inherited Members
2134class SegmentedIO(RawIOBaseWSeek): 2135 """A stream that combines several existing streams""" 2136 class Segment(Tuple): 2137 start = file = offset = size = ... 2138 2139 def __init__(m): 2140 m.segments = [] 2141 m.last_segment = None 2142 m.position = 0 2143 m.length = 0 2144 2145 def add(m, file, offset, size): 2146 m.segments.append(m.Segment(m.length, file, offset, size)) 2147 m.length += size 2148 2149 def flush(m): 2150 for segment in m.segments: 2151 segment.file.flush() 2152 2153 def _find(m, offset): 2154 segment = m.last_segment 2155 if segment and segment.start <= offset < segment.start + segment.size: 2156 return segment, offset - segment.start 2157 2158 for segment in m.segments: 2159 if segment.start <= offset < segment.start + segment.size: 2160 m.last_segment = segment 2161 return segment, offset - segment.start 2162 2163 return None, 0 2164 2165 def readinto(m, target): 2166 offset = 0 2167 size = len(target) 2168 view = memoryview(target) 2169 2170 while offset < size: 2171 segment, offset_in_seg = m._find(m.position) 2172 if segment is None: 2173 break 2174 2175 segment.file.seek(segment.offset + offset_in_seg) 2176 seg_count = min(segment.size - offset_in_seg, size - offset) 2177 seg_count = segment.file.readinto(view[offset : offset + seg_count]) 2178 if seg_count is None: 2179 return offset if offset else None 2180 2181 if seg_count == 0: 2182 break 2183 2184 offset += seg_count 2185 m.position += seg_count 2186 2187 return offset 2188 2189 def write(m, data): 2190 offset = 0 2191 size = len(data) 2192 view = memoryview(data) 2193 2194 while offset < size: 2195 segment, offset_in_seg = m._find(m.position) 2196 if segment is None: 2197 break 2198 2199 segment.file.seek(segment.offset + offset_in_seg) 2200 seg_count = min(segment.size - offset_in_seg, size - offset) 2201 seg_count = segment.file.write(view[offset : offset + seg_count]) 2202 if seg_count is None: 2203 return offset if offset else None 2204 2205 if seg_count == 0: 2206 break 2207 2208 offset += seg_count 2209 m.position += seg_count 2210 2211 return offset
A stream that combines several existing streams
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
2165 def readinto(m, target): 2166 offset = 0 2167 size = len(target) 2168 view = memoryview(target) 2169 2170 while offset < size: 2171 segment, offset_in_seg = m._find(m.position) 2172 if segment is None: 2173 break 2174 2175 segment.file.seek(segment.offset + offset_in_seg) 2176 seg_count = min(segment.size - offset_in_seg, size - offset) 2177 seg_count = segment.file.readinto(view[offset : offset + seg_count]) 2178 if seg_count is None: 2179 return offset if offset else None 2180 2181 if seg_count == 0: 2182 break 2183 2184 offset += seg_count 2185 m.position += seg_count 2186 2187 return offset
2189 def write(m, data): 2190 offset = 0 2191 size = len(data) 2192 view = memoryview(data) 2193 2194 while offset < size: 2195 segment, offset_in_seg = m._find(m.position) 2196 if segment is None: 2197 break 2198 2199 segment.file.seek(segment.offset + offset_in_seg) 2200 seg_count = min(segment.size - offset_in_seg, size - offset) 2201 seg_count = segment.file.write(view[offset : offset + seg_count]) 2202 if seg_count is None: 2203 return offset if offset else None 2204 2205 if seg_count == 0: 2206 break 2207 2208 offset += seg_count 2209 m.position += seg_count 2210 2211 return offset
Inherited Members
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, const base fields keyword parameters Atributes with a name ending with _ can be referred to without the _.
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
2213class ByteArrayIO(RawIOBaseWSeek): 2214 """Exposes a bytearray as a stream""" # did I miss this in the stdlib? 2215 def __init__(m, arr): 2216 m.arr = arr 2217 m.position = 0 2218 2219 @property 2220 def length(m): 2221 return len(m.arr) 2222 2223 def readinto(m, target): 2224 pos = m.position 2225 slice = m.arr[pos:pos + len(target)] 2226 count = len(slice) 2227 target[:count] = slice 2228 m.position += count 2229 return count 2230 2231 def write(m, data): 2232 pos = m.position 2233 if pos > len(m.arr): # slice syntax doesn't handle this case... 2234 m.arr += bytearray(pos - len(m.arr)) 2235 size = len(data) 2236 m.arr[pos:pos + size] = data 2237 m.position += size 2238 return size
Exposes a bytearray as a stream
Inherited Members
2248class CustomPath(str): 2249 """A path that refers to some custom-obtained data""" 2250 2251 def open(m): 2252 raise FileNotFoundError(type(m)) 2253 def open_text(m, encoding, errors, newline): 2254 raise FileNotFoundError(type(m)) 2255 def create(m): 2256 raise FileNotFoundError(type(m)) 2257 def create_text(m, encoding, errors, newline): 2258 raise FileNotFoundError(type(m))
A path that refers to some custom-obtained data
2263class StdPath(CustomPath): 2264 """A path that refers to the standard streams""" 2265 2266 def open(m): 2267 return IOWrapper(sys.stdin.buffer) 2268 2269 def open_text(m, encoding, errors, newline): 2270 sys.stdin.reconfigure(encoding=encoding, errors=errors, newline=newline) 2271 return IOWrapper(sys.stdin) 2272 2273 def create(m): 2274 return IOWrapper(sys.stdout.buffer) 2275 2276 def create_text(m, encoding, errors, newline): 2277 sys.stdout.reconfigure(encoding=encoding, errors=errors, newline=newline) 2278 return IOWrapper(sys.stdout) 2279 2280 append = create 2281 append_text = create_text
A path that refers to the standard streams
2283class DataPath(CustomPath): 2284 """A path that refers to some data""" 2285 2286 def __new__(cls, value, data): 2287 path = str.__new__(cls, value) 2288 path.data = data 2289 return path 2290 2291 def open(m): 2292 return BytesIO(m.data) 2293 2294 def open_text(m, encoding, errors, newline): 2295 return StringIO(m.data.decode(encoding, errors), newline=newline)
A path that refers to some data
Inherited Members
2297class URLPath(CustomPath): 2298 """A path that's actually a URL""" 2299 2300 def open(m): 2301 from urllib.request import urlopen 2302 return urlopen(m) 2303 2304 def open_text(m, encoding, errors, newline): 2305 return io.TextIOWrapper(m.open(), encoding, errors, newline)
A path that's actually a URL
Inherited Members
2307def file_open(path): 2308 """Open a binary file for reading""" 2309 if isinstance(path, CustomPath): 2310 return path.open() 2311 else: 2312 return open(path, "rb")
Open a binary file for reading
2314def file_open_text(path, encoding = "utf-8", errors = None, newline = None): 2315 """Open a text file for reading""" 2316 if isinstance(path, CustomPath): 2317 return path.open_text(encoding, errors, newline) 2318 else: 2319 return open(path, "r", encoding=encoding, errors=errors, newline=newline)
Open a text file for reading
2324def file_create(path): 2325 """Create or replace a binary file for writing""" 2326 if isinstance(path, CustomPath): 2327 return path.create() 2328 else: 2329 return open(path, "wb")
Create or replace a binary file for writing
2331def file_create_text(path, encoding = "utf-8", errors = None, newline = "\n"): 2332 """Create or replace a text file for writing""" 2333 if isinstance(path, CustomPath): 2334 return path.create_text(encoding, errors, newline) 2335 else: 2336 return open(path, "w", encoding=encoding, errors=errors, newline=newline)
Create or replace a text file for writing
2341def file_prepare_append(path): 2342 """Open or create a binary file for appending""" 2343 if isinstance(path, CustomPath): 2344 return path.append() 2345 else: 2346 return open(path, "ab")
Open or create a binary file for appending
2348def file_prepare_append_text(path, encoding = "utf-8", errors = None, newline = "\n"): 2349 """Open or create a text file for appending""" 2350 if isinstance(path, CustomPath): 2351 return path.append_text(encoding, errors, newline) 2352 else: 2353 return open(path, "a", encoding=encoding, errors=errors, newline=newline)
Open or create a text file for appending
2358def file_read(path, offset = 0, size = None): 2359 """Read all data from a binary file (or optionally, a subset of data)""" 2360 with file_open(path) as f: 2361 if offset: 2362 f.seek(offset, 0) 2363 if size: 2364 return f.read(size) 2365 else: 2366 return f.read()
Read all data from a binary file (or optionally, a subset of data)
2368def file_read_text(path, encoding = "utf-8", errors = None, newline = None): 2369 """Read all text from a text file""" 2370 with file_open_text(path, encoding, errors, newline) as f: 2371 return f.read()
Read all text from a text file
2376def file_read_json(path, **json_kwargs): 2377 """Read data from a json file""" 2378 with file_open_text(path) as f: 2379 return json.load(f, **json_kwargs)
Read data from a json file
2381def file_write(path, value): 2382 """Create or replace a binary file, writing 'value' into it""" 2383 with file_create(path) as f: 2384 f.write(value)
Create or replace a binary file, writing 'value' into it
2386def file_write_text(path, value, encoding = "utf-8", errors = None, newline = "\n"): 2387 """Create or replace a text file, writing 'value' into it""" 2388 with file_create_text(path, encoding, errors, newline) as f: 2389 f.write(value)
Create or replace a text file, writing 'value' into it
2394def file_write_json(path, value, **json_kwargs): 2395 """Create or replace a json file, writing 'data' into it""" 2396 with file_create_text(path) as f: 2397 json.dump(value, f, **json_kwargs)
Create or replace a json file, writing 'data' into it
2399def file_append(path, value): 2400 """Open or create a binary file, appending 'value' into it""" 2401 with file_prepare_append(path) as f: 2402 f.write(value)
Open or create a binary file, appending 'value' into it
2404def file_append_text(path, value, encoding = "utf-8", errors = None, newline = "\n"): 2405 """Open or create a text file, appending 'value' into it""" 2406 with file_prepare_append_text(path, encoding, errors, newline) as f: 2407 f.write(value)
Open or create a text file, appending 'value' into it
2412def try_file_read(path, defval = None): 2413 """Try reading all data from a binary file, or return 'defval' on any error""" 2414 try: 2415 return file_read(path) 2416 except Exception: 2417 return defval
Try reading all data from a binary file, or return 'defval' on any error
2419def try_file_read_text(path, defval = None, encoding = "utf-8", errors = None, newline = None): 2420 """Try reading all text from a text file, or return 'defval' on any error""" 2421 try: 2422 return file_read_text(path, encoding, errors, newline) 2423 except Exception: 2424 return defval
Try reading all text from a text file, or return 'defval' on any error
2429def try_file_read_json(path, defval = None, **json_kwargs): 2430 """Try reading data from a json file, or return 'defval' on any error""" 2431 try: 2432 return file_read_json(path, **json_kwargs) 2433 except Exception: 2434 return defval
Try reading data from a json file, or return 'defval' on any error
2436def try_file_write(path, value): 2437 """Try creating or replacing a binary file, writing 'value' into it. Return if succeeded""" 2438 try: 2439 file_write(path, value) 2440 return True 2441 except Exception: 2442 return False
Try creating or replacing a binary file, writing 'value' into it. Return if succeeded
2444def try_file_write_text(path, value, encoding = "utf-8", errors = None, newline = "\n"): 2445 """Try creating or replacing a text file, writing 'value' into it. Return if succeeded""" 2446 try: 2447 file_write_text(path, value, encoding, errors, newline) 2448 return True 2449 except Exception: 2450 return False
Try creating or replacing a text file, writing 'value' into it. Return if succeeded
2455def try_file_write_json(path, value, **json_kwargs): 2456 """Try creating or replacing a json file, writing 'value' into it. Return if succeeded""" 2457 try: 2458 file_write_json(path, value, **json_kwargs) 2459 return True 2460 except Exception: 2461 return False
Try creating or replacing a json file, writing 'value' into it. Return if succeeded
2463def file_delete(path): 2464 """Delete a file if it exists""" 2465 try: 2466 os.remove(path) 2467 return True 2468 except FileNotFoundError: 2469 return False
Delete a file if it exists
2463def file_delete(path): 2464 """Delete a file if it exists""" 2465 try: 2466 os.remove(path) 2467 return True 2468 except FileNotFoundError: 2469 return False
Delete a file if it exists
2473def file_temp(): 2474 """Create a temporary file (no auto-deletion)""" 2475 result = tempfile.NamedTemporaryFile(delete=False) 2476 result.close() 2477 return result.name
Create a temporary file (no auto-deletion)
101def split(p): 102 """Split a pathname. Returns tuple "(head, tail)" where "tail" is 103 everything after the final slash. Either part may be empty.""" 104 p = os.fspath(p) 105 sep = _get_sep(p) 106 i = p.rfind(sep) + 1 107 head, tail = p[:i], p[i:] 108 if head and head != sep*len(head): 109 head = head.rstrip(sep) 110 return head, tail
Split a pathname. Returns tuple "(head, tail)" where "tail" is everything after the final slash. Either part may be empty.
167def basename(p): 168 """Returns the final component of a pathname""" 169 p = os.fspath(p) 170 sep = _get_sep(p) 171 i = p.rfind(sep) + 1 172 return p[i:]
Returns the final component of a pathname
177def dirname(p): 178 """Returns the directory component of a pathname""" 179 p = os.fspath(p) 180 sep = _get_sep(p) 181 i = p.rfind(sep) + 1 182 head = p[:i] 183 if head and head != sep*len(head): 184 head = head.rstrip(sep) 185 return head
Returns the directory component of a pathname
374def abspath(path): 375 """Return an absolute path.""" 376 path = os.fspath(path) 377 if isinstance(path, bytes): 378 if not path.startswith(b'/'): 379 path = join(os.getcwdb(), path) 380 else: 381 if not path.startswith('/'): 382 path = join(os.getcwd(), path) 383 return normpath(path)
Return an absolute path.
118def splitext(p): 119 p = os.fspath(p) 120 if isinstance(p, bytes): 121 sep = b'/' 122 extsep = b'.' 123 else: 124 sep = '/' 125 extsep = '.' 126 return genericpath._splitext(p, sep, None, extsep)
Split the extension from a pathname.
Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty.
389def realpath(filename, *, strict=False): 390 """Return the canonical path of the specified filename, eliminating any 391symbolic links encountered in the path.""" 392 filename = os.fspath(filename) 393 if isinstance(filename, bytes): 394 sep = b'/' 395 curdir = b'.' 396 pardir = b'..' 397 getcwd = os.getcwdb 398 else: 399 sep = '/' 400 curdir = '.' 401 pardir = '..' 402 getcwd = os.getcwd 403 if strict is ALLOW_MISSING: 404 ignored_error = FileNotFoundError 405 strict = True 406 elif strict: 407 ignored_error = () 408 else: 409 ignored_error = OSError 410 411 lstat = os.lstat 412 readlink = os.readlink 413 maxlinks = None 414 415 # The stack of unresolved path parts. When popped, a special value of None 416 # indicates that a symlink target has been resolved, and that the original 417 # symlink path can be retrieved by popping again. The [::-1] slice is a 418 # very fast way of spelling list(reversed(...)). 419 rest = filename.split(sep)[::-1] 420 421 # Number of unprocessed parts in 'rest'. This can differ from len(rest) 422 # later, because 'rest' might contain markers for unresolved symlinks. 423 part_count = len(rest) 424 425 # The resolved path, which is absolute throughout this function. 426 # Note: getcwd() returns a normalized and symlink-free path. 427 path = sep if filename.startswith(sep) else getcwd() 428 429 # Mapping from symlink paths to *fully resolved* symlink targets. If a 430 # symlink is encountered but not yet resolved, the value is None. This is 431 # used both to detect symlink loops and to speed up repeated traversals of 432 # the same links. 433 seen = {} 434 435 # Number of symlinks traversed. When the number of traversals is limited 436 # by *maxlinks*, this is used instead of *seen* to detect symlink loops. 437 link_count = 0 438 439 while part_count: 440 name = rest.pop() 441 if name is None: 442 # resolved symlink target 443 seen[rest.pop()] = path 444 continue 445 part_count -= 1 446 if not name or name == curdir: 447 # current dir 448 continue 449 if name == pardir: 450 # parent dir 451 path = path[:path.rindex(sep)] or sep 452 continue 453 if path == sep: 454 newpath = path + name 455 else: 456 newpath = path + sep + name 457 try: 458 st_mode = lstat(newpath).st_mode 459 if not stat.S_ISLNK(st_mode): 460 if strict and part_count and not stat.S_ISDIR(st_mode): 461 raise OSError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), 462 newpath) 463 path = newpath 464 continue 465 elif maxlinks is not None: 466 link_count += 1 467 if link_count > maxlinks: 468 if strict: 469 raise OSError(errno.ELOOP, os.strerror(errno.ELOOP), 470 newpath) 471 path = newpath 472 continue 473 elif newpath in seen: 474 # Already seen this path 475 path = seen[newpath] 476 if path is not None: 477 # use cached value 478 continue 479 # The symlink is not resolved, so we must have a symlink loop. 480 if strict: 481 raise OSError(errno.ELOOP, os.strerror(errno.ELOOP), 482 newpath) 483 path = newpath 484 continue 485 target = readlink(newpath) 486 except ignored_error: 487 pass 488 else: 489 # Resolve the symbolic link 490 if target.startswith(sep): 491 # Symlink target is absolute; reset resolved path. 492 path = sep 493 if maxlinks is None: 494 # Mark this symlink as seen but not fully resolved. 495 seen[newpath] = None 496 # Push the symlink path onto the stack, and signal its specialness 497 # by also pushing None. When these entries are popped, we'll 498 # record the fully-resolved symlink target in the 'seen' mapping. 499 rest.append(newpath) 500 rest.append(None) 501 # Push the unresolved symlink target parts onto the stack. 502 target_parts = target.split(sep)[::-1] 503 rest.extend(target_parts) 504 part_count += len(target_parts) 505 continue 506 # An error occurred and was ignored. 507 path = newpath 508 509 return path
Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path.
2486def path_extension(path): 2487 """Return the extension of a path""" 2488 return os.path.splitext(path)[1]
Return the extension of a path
2490def path_no_extension(path): 2491 """Return the path without an extension""" 2492 return os.path.splitext(path)[0]
Return the path without an extension
2494def path_basename_no_extension(path): 2495 """Return the basename of the path without an extension""" 2496 return path_no_extension(path_basename(path))
Return the basename of the path without an extension
2498def path_split_comps(path): 2499 """Split the path to its components(dir/basenames)""" 2500 comps = [] 2501 while True: 2502 path, comp = path_split_name(path) 2503 if comp: 2504 comps.append(comp) 2505 elif path: 2506 comps.append(path) 2507 else: 2508 break 2509 comps.reverse() 2510 return comps
Split the path to its components(dir/basenames)
2530def path_modify_time(path): 2531 """Return the modify time of the file/directory at the given path""" 2532 return datetime.fromtimestamp(os.path.getmtime(path))
Return the modify time of the file/directory at the given path
73def join(a, *p): 74 """Join two or more pathname components, inserting '/' as needed. 75 If any component is an absolute path, all previous path components 76 will be discarded. An empty last part will result in a path that 77 ends with a separator.""" 78 a = os.fspath(a) 79 sep = _get_sep(a) 80 path = a 81 try: 82 for b in p: 83 b = os.fspath(b) 84 if b.startswith(sep) or not path: 85 path = b 86 elif path.endswith(sep): 87 path += b 88 else: 89 path += sep + b 90 except (TypeError, AttributeError, BytesWarning): 91 genericpath._check_arg_types('join', a, *p) 92 raise 93 return path
Join two or more pathname components, inserting '/' as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.
62def isabs(s): 63 """Test whether a path is absolute""" 64 s = os.fspath(s) 65 sep = _get_sep(s) 66 return s.startswith(sep)
Test whether a path is absolute
17def exists(path): 18 """Test whether a path exists. Returns False for broken symbolic links""" 19 try: 20 os.stat(path) 21 except (OSError, ValueError): 22 return False 23 return True
Test whether a path exists. Returns False for broken symbolic links
49def isdir(s): 50 """Return true if the pathname refers to an existing directory.""" 51 try: 52 st = os.stat(s) 53 except (OSError, ValueError): 54 return False 55 return stat.S_ISDIR(st.st_mode)
Return true if the pathname refers to an existing directory.
37def isfile(path): 38 """Test whether a path is a regular file""" 39 try: 40 st = os.stat(path) 41 except (OSError, ValueError): 42 return False 43 return stat.S_ISREG(st.st_mode)
Test whether a path is a regular file
2540def path_ensure_dir_exists(path): 2541 """If the directory of 'path' doesn't exist, create it""" 2542 dir_ensure_exists(path_dirname(path))
If the directory of 'path' doesn't exist, create it
2544def dir_ensure_exists(path): 2545 """If the directory 'path' doesn't exist, create it""" 2546 try: 2547 os.makedirs(path) 2548 except FileExistsError: 2549 pass
If the directory 'path' doesn't exist, create it
2551def dir_create(path, delete_existing=False): 2552 """Create a directory, optionally deleting any existing files in it first""" 2553 if delete_existing and path_exists(path): 2554 shutil.rmtree(path) 2555 dir_ensure_exists(path)
Create a directory, optionally deleting any existing files in it first
2557def dir_names(path): 2558 """Return the names of the contents of the directory""" 2559 return os.listdir(path)
Return the names of the contents of the directory
2561def dir_paths(path): 2562 """Return the full paths of the contents of the directory""" 2563 return (path_join(path, file) for file in dir_names(path))
Return the full paths of the contents of the directory
Return a unicode string representing the current working directory.
Change the current working directory to the specified path.
path may always be specified as a string. On some platforms, path may also be specified as an open file descriptor. If this functionality is unavailable, using it raises an exception.
2568def try_dir_names(path, defval = None): 2569 """Try returning the names of the contents of the directory""" 2570 try: 2571 return dir_names(path) 2572 except Exception: 2573 return defval
Try returning the names of the contents of the directory
2575def try_dir_paths(path, defval = None): 2576 """Try returning the full paths of the contents of the directory""" 2577 try: 2578 return dir_paths(path) 2579 except Exception: 2580 return defval
Try returning the full paths of the contents of the directory
2582def filename_fixup(filename): 2583 """Fixup a filename to be valid""" 2584 fixed = "".join([ch if ch not in r"\/:*?<>|" else "_" for ch in filename]) 2585 if not fixed or fixed.endswith("."): 2586 fixed += "_" 2587 return fixed
Fixup a filename to be valid
2589def try_cast(value, ctor, defval=None): 2590 """Try converting 'value' via constructor 'ctor', return 'defval' on failure""" 2591 try: 2592 return ctor(value) 2593 except ValueError: 2594 return defval
Try converting 'value' via constructor 'ctor', return 'defval' on failure
2596def maybe_int(value, defval=None, base=10): 2597 """Try converting 'value' to an int, return 'defval' on failure""" 2598 if value is None: 2599 return defval 2600 try: 2601 return int(value, base) 2602 except ValueError: 2603 return defval
Try converting 'value' to an int, return 'defval' on failure
2605def maybe_float(value, defval=None, base=10): 2606 """Try converting 'value' to a float, return 'defval' on failure""" 2607 if value is None: 2608 return defval 2609 try: 2610 if base == 0: 2611 base = 16 if value.lower().startswith("0x") else 10 2612 2613 if base == 10: 2614 return float(value) 2615 elif base == 16: 2616 return float.fromhex(value) 2617 else: 2618 return defval 2619 except ValueError: 2620 return defval
Try converting 'value' to a float, return 'defval' on failure
2622def maybe_num(value, defval=None, base=10): 2623 """Try converting 'value' to an int or float, return 'defval' on failure""" 2624 result = maybe_int(value, base=base) 2625 if result is None: 2626 result = maybe_float(value, base=base) 2627 if result is None: 2628 result = defval 2629 return result
Try converting 'value' to an int or float, return 'defval' on failure
2631def count_significant_bits(a): 2632 """Return how many significant bits (all but leading zero bits) 'a' has""" 2633 assert a >= 0 2634 return a.bit_length()
Return how many significant bits (all but leading zero bits) 'a' has
2636def count_leading_zero_bits(a, bits): 2637 """Return how many leading zero bits 'a' has, counting from 'bits'""" 2638 assert a >= 0 2639 return bits - a.bit_length()
Return how many leading zero bits 'a' has, counting from 'bits'
2641def count_trailing_zero_bits(a): 2642 """Return how many trailing zero bits 'a' has""" 2643 assert a >= 0 2644 count = 0 2645 while not (a & 0xff): 2646 count += 8 2647 a >>= 8 2648 while not (a & 0x1): 2649 count += 1 2650 a >>= 1 2651 return count
Return how many trailing zero bits 'a' has
2653def make_mask(pos, size): 2654 """Create a mask with 'size' ones at bit 'pos'""" 2655 return ((1 << size) - 1) << pos
Create a mask with 'size' ones at bit 'pos'
2657def is_pow2(a): 2658 """Return if 'a' is a power of 2""" 2659 return a > 0 and (a & (a - 1)) == 0
Return if 'a' is a power of 2
2661def div_up(a, b): 2662 """Divide 'a' by 'b', rounding up""" 2663 r, m = divmod(a, b) 2664 return r + 1 if m else r
Divide 'a' by 'b', rounding up
2666def quotrem(a, b): 2667 """Return the quotient and remainder of dividing 'a' by 'b'""" 2668 q, r = divmod(a, b) 2669 if q < 0 and r != 0: 2670 q += 1 2671 r -= b 2672 return q, r
Return the quotient and remainder of dividing 'a' by 'b'
2674def quot(a, b): 2675 """Return the quotient of dividing 'a' by 'b'""" 2676 return quotrem(a, b)[0]
Return the quotient of dividing 'a' by 'b'
2678def rem(a, b): 2679 """Return the remainder of dividing 'a' by 'b'""" 2680 return quotrem(a, b)[1]
Return the remainder of dividing 'a' by 'b'
2682def round_down(a, b): 2683 """Round 'a' down by 'b'""" 2684 m = a % b 2685 return a - m if m else a
Round 'a' down by 'b'
2687def round_up(a, b): 2688 """Round 'a' up by 'b'""" 2689 assert b > 0 2690 m = a % b 2691 return a + (b - m) if m else a
Round 'a' up by 'b'
2693def round_up_pow2(a): 2694 """Round 'a' up to its next power of 2""" 2695 assert a > 0 2696 return 1 << (a - 1).bit_length()
Round 'a' up to its next power of 2
Square 'value'
2702def clamp(value, minval, maxval): 2703 """Return 'value' clamped between 'minval' and 'maxval'""" 2704 return minval if value < minval else maxval if value > maxval else value
Return 'value' clamped between 'minval' and 'maxval'
2702def clamp(value, minval, maxval): 2703 """Return 'value' clamped between 'minval' and 'maxval'""" 2704 return minval if value < minval else maxval if value > maxval else value
Return 'value' clamped between 'minval' and 'maxval'
2708def lerp(start, end, portion): 2709 """Return the linear interpolation between 'start' and 'end'""" 2710 return start + portion * (end - start)
Return the linear interpolation between 'start' and 'end'
2712def rotate_left(value, count, bits): 2713 """Rotate 'value' left by 'count' bits, across 'bits' bits""" 2714 assert value >= 0 2715 count %= bits 2716 return ((value << count) | (value >> (bits - count))) & make_mask(0, bits)
Rotate 'value' left by 'count' bits, across 'bits' bits
2718def rotate_right(value, count, bits): 2719 """Rotate 'value' right by 'count' bits, across 'bits' bits""" 2720 assert value >= 0 2721 count %= bits 2722 return ((value >> count) | (value << (bits - count))) & make_mask(0, bits)
Rotate 'value' right by 'count' bits, across 'bits' bits
2724def closure(__func, *args, **kwargs): 2725 """Create a lambda that applies the given arguments to 'func'""" 2726 return lambda: __func(*args, **kwargs)
Create a lambda that applies the given arguments to 'func'
2728def debug(*msg): 2729 """Print a message only if debugging is enabled""" 2730 if debug.enabled: 2731 eprint(*msg)
Print a message only if debugging is enabled
2735def warn_assert(cond, msg): 2736 """Warn if 'cond' is false""" 2737 if not cond: 2738 warn(msg) 2739 return cond
Warn if 'cond' is false
Fail, optionally with message
2745class CheckError(Exception): 2746 """An error meant to be caught and displayed as-is, like AssertionError but for user errors"""
An error meant to be caught and displayed as-is, like AssertionError but for user errors
2748def check(cond, msg): 2749 """If condition doesn't hold, raise CheckError""" 2750 if not cond: 2751 raise CheckError(msg)
If condition doesn't hold, raise CheckError
Unconditionally raise CheckError
2757def desc(value): 2758 """Set a description (desc attr) of the given function""" 2759 def decorator(f): 2760 f.desc = value 2761 return f 2762 return decorator
Set a description (desc attr) of the given function
2764def trace(*args): 2765 """Print with traceback""" 2766 eprint(*args) 2767 traceback.print_stack()
Print with traceback
Return bytes from a single byte
2773def measure_execution_time(func): 2774 """Decorator to measure execution time of a function""" 2775 def decorator(*args, **kwargs): 2776 start = time.time() 2777 result = func(*args, **kwargs) 2778 end = time.time() 2779 eprint(f"{func} took {end - start:f} seconds") 2780 return result 2781 return decorator
Decorator to measure execution time of a function