utils.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. import ast
  2. import itertools
  3. import types
  4. from collections import OrderedDict, Counter, defaultdict
  5. from types import FrameType, TracebackType
  6. from typing import (
  7. Iterator, List, Tuple, Iterable, Callable, Union,
  8. TypeVar, Mapping,
  9. )
  10. T = TypeVar('T')
  11. R = TypeVar('R')
  12. def truncate(seq, max_length: int, middle):
  13. if len(seq) > max_length:
  14. right = (max_length - len(middle)) // 2
  15. left = max_length - len(middle) - right
  16. seq = seq[:left] + middle + seq[-right:]
  17. return seq
  18. def unique_in_order(it: Iterable[T]) -> List[T]:
  19. return list(OrderedDict.fromkeys(it))
  20. def line_range(node: ast.AST) -> Tuple[int, int]:
  21. """
  22. Returns a pair of numbers representing a half open range
  23. (i.e. suitable as arguments to the `range()` builtin)
  24. of line numbers of the given AST nodes.
  25. """
  26. try:
  27. return (
  28. node.first_token.start[0],
  29. node.last_token.end[0] + 1,
  30. )
  31. except AttributeError:
  32. return (
  33. node.lineno,
  34. getattr(node, "end_lineno", node.lineno) + 1,
  35. )
  36. def highlight_unique(lst: List[T]) -> Iterator[Tuple[T, bool]]:
  37. counts = Counter(lst)
  38. for is_common, group in itertools.groupby(lst, key=lambda x: counts[x] > 3):
  39. if is_common:
  40. group = list(group)
  41. highlighted = [False] * len(group)
  42. def highlight_index(f):
  43. try:
  44. i = f()
  45. except ValueError:
  46. return None
  47. highlighted[i] = True
  48. return i
  49. for item in set(group):
  50. first = highlight_index(lambda: group.index(item))
  51. if first is not None:
  52. highlight_index(lambda: group.index(item, first + 1))
  53. highlight_index(lambda: -1 - group[::-1].index(item))
  54. else:
  55. highlighted = itertools.repeat(True)
  56. yield from zip(group, highlighted)
  57. def identity(x: T) -> T:
  58. return x
  59. def collapse_repeated(lst, *, collapser, mapper=identity, key=identity):
  60. keyed = list(map(key, lst))
  61. for is_highlighted, group in itertools.groupby(
  62. zip(lst, highlight_unique(keyed)),
  63. key=lambda t: t[1][1],
  64. ):
  65. original_group, highlighted_group = zip(*group)
  66. if is_highlighted:
  67. yield from map(mapper, original_group)
  68. else:
  69. keyed_group, _ = zip(*highlighted_group)
  70. yield collapser(list(original_group), list(keyed_group))
  71. def is_frame(frame_or_tb: Union[FrameType, TracebackType]) -> bool:
  72. assert_(isinstance(frame_or_tb, (types.FrameType, types.TracebackType)))
  73. return isinstance(frame_or_tb, (types.FrameType,))
  74. def iter_stack(frame_or_tb: Union[FrameType, TracebackType]) -> Iterator[Union[FrameType, TracebackType]]:
  75. while frame_or_tb:
  76. yield frame_or_tb
  77. if is_frame(frame_or_tb):
  78. frame_or_tb = frame_or_tb.f_back
  79. else:
  80. frame_or_tb = frame_or_tb.tb_next
  81. def frame_and_lineno(frame_or_tb: Union[FrameType, TracebackType]) -> Tuple[FrameType, int]:
  82. if is_frame(frame_or_tb):
  83. return frame_or_tb, frame_or_tb.f_lineno
  84. else:
  85. return frame_or_tb.tb_frame, frame_or_tb.tb_lineno
  86. def group_by_key_func(iterable: Iterable[T], key_func: Callable[[T], R]) -> Mapping[R, List[T]]:
  87. # noinspection PyUnresolvedReferences
  88. """
  89. Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements
  90. of the iterable and the values are lists of elements all of which correspond to the key.
  91. >>> def si(d): return sorted(d.items())
  92. >>> si(group_by_key_func("a bb ccc d ee fff".split(), len))
  93. [(1, ['a', 'd']), (2, ['bb', 'ee']), (3, ['ccc', 'fff'])]
  94. >>> si(group_by_key_func([-1, 0, 1, 3, 6, 8, 9, 2], lambda x: x % 2))
  95. [(0, [0, 6, 8, 2]), (1, [-1, 1, 3, 9])]
  96. """
  97. result = defaultdict(list)
  98. for item in iterable:
  99. result[key_func(item)].append(item)
  100. return result
  101. class cached_property(object):
  102. """
  103. A property that is only computed once per instance and then replaces itself
  104. with an ordinary attribute. Deleting the attribute resets the property.
  105. Based on https://github.com/pydanny/cached-property/blob/master/cached_property.py
  106. """
  107. def __init__(self, func):
  108. self.__doc__ = func.__doc__
  109. self.func = func
  110. def cached_property_wrapper(self, obj, _cls):
  111. if obj is None:
  112. return self
  113. value = obj.__dict__[self.func.__name__] = self.func(obj)
  114. return value
  115. __get__ = cached_property_wrapper
  116. def _pygmented_with_ranges(formatter, code, ranges):
  117. import pygments
  118. from pygments.lexers import get_lexer_by_name
  119. class MyLexer(type(get_lexer_by_name("python3"))):
  120. def get_tokens(self, text):
  121. length = 0
  122. for ttype, value in super().get_tokens(text):
  123. if any(start <= length < end for start, end in ranges):
  124. ttype = ttype.ExecutingNode
  125. length += len(value)
  126. yield ttype, value
  127. lexer = MyLexer(stripnl=False)
  128. return pygments.highlight(code, lexer, formatter).splitlines()
  129. def assert_(condition, error=""):
  130. if not condition:
  131. if isinstance(error, str):
  132. error = AssertionError(error)
  133. raise error