More mypy cleanup.
authorScott <[email protected]>
Wed, 2 Feb 2022 16:31:42 +0000 (08:31 -0800)
committerScott <[email protected]>
Wed, 2 Feb 2022 16:31:42 +0000 (08:31 -0800)
ansi.py
exec_utils.py
histogram.py
text_utils.py

diff --git a/ansi.py b/ansi.py
index 9e31b811ab978fa1ae81c3974ba991700287d867..6897291ba252f91c866b967cd18e0aa13f0f151d 100755 (executable)
--- a/ansi.py
+++ b/ansi.py
@@ -1890,19 +1890,19 @@ def bg(
 
 class StdoutInterceptor(io.TextIOBase):
     def __init__(self):
-        self.saved_stdout: Optional[io.TextIOBase] = None
+        self.saved_stdout: io.TextIO = None
         self.buf = ''
 
     @abstractmethod
     def write(self, s: str):
         pass
 
-    def __enter__(self) -> None:
+    def __enter__(self):
         self.saved_stdout = sys.stdout
         sys.stdout = self
-        return None
+        return self
 
-    def __exit__(self, *args) -> bool:
+    def __exit__(self, *args) -> Optional[bool]:
         sys.stdout = self.saved_stdout
         print(self.buf)
         return None
index dcd30a2e937e271ffe75109c019b3b345fa5997d..061370ff012a543c29f75f32b4996eaee3dbf0f8 100644 (file)
@@ -31,12 +31,12 @@ def cmd_showing_output(
         stderr=subprocess.PIPE,
         universal_newlines=False,
     ) as p:
-        sel.register(p.stdout, selectors.EVENT_READ)
-        sel.register(p.stderr, selectors.EVENT_READ)
+        sel.register(p.stdout, selectors.EVENT_READ)  # type: ignore
+        sel.register(p.stderr, selectors.EVENT_READ)  # type: ignore
         done = False
         while not done:
             for key, _ in sel.select():
-                char = key.fileobj.read(1)
+                char = key.fileobj.read(1)  # type: ignore
                 if not char:
                     sel.unregister(key.fileobj)
                     if len(sel.get_map()) == 0:
index 87ef77340fd036b8ea29d5ddf3def5d902db3688..993b5036d737cdcd705ef411e5cbcf70ba0da911 100644 (file)
@@ -2,46 +2,49 @@
 
 import math
 from numbers import Number
-from typing import Generic, Iterable, List, Optional, Tuple, TypeVar
+from typing import Dict, Generic, Iterable, List, Optional, Tuple, TypeVar
 
-T = TypeVar("T", bound=Number)
+T = TypeVar("T", int, float)
+Bound = int
+Count = int
 
 
 class SimpleHistogram(Generic[T]):
-
     # Useful in defining wide open bottom/top bucket bounds:
     POSITIVE_INFINITY = math.inf
     NEGATIVE_INFINITY = -math.inf
 
-    def __init__(self, buckets: List[Tuple[T, T]]):
+    def __init__(self, buckets: List[Tuple[Bound, Bound]]):
         from math_utils import RunningMedian
 
-        self.buckets = {}
+        self.buckets: Dict[Tuple[Bound, Bound], Count] = {}
         for start_end in buckets:
             if self._get_bucket(start_end[0]) is not None:
                 raise Exception("Buckets overlap?!")
             self.buckets[start_end] = 0
-        self.sigma = 0
-        self.median = RunningMedian()
-        self.maximum = None
-        self.minimum = None
-        self.count = 0
+        self.sigma: float = 0.0
+        self.median: RunningMedian = RunningMedian()
+        self.maximum: Optional[T] = None
+        self.minimum: Optional[T] = None
+        self.count: Count = 0
 
     @staticmethod
     def n_evenly_spaced_buckets(
         min_bound: T,
         max_bound: T,
         n: int,
-    ) -> List[Tuple[T, T]]:
-        ret = []
+    ) -> List[Tuple[int, int]]:
+        ret: List[Tuple[int, int]] = []
         stride = int((max_bound - min_bound) / n)
         if stride <= 0:
             raise Exception("Min must be < Max")
-        for bucket_start in range(min_bound, max_bound, stride):
+        imax = math.ceil(max_bound)
+        imin = math.floor(min_bound)
+        for bucket_start in range(imin, imax, stride):
             ret.append((bucket_start, bucket_start + stride))
         return ret
 
-    def _get_bucket(self, item: T) -> Optional[Tuple[T, T]]:
+    def _get_bucket(self, item: T) -> Optional[Tuple[int, int]]:
         for start_end in self.buckets:
             if start_end[0] <= item < start_end[1]:
                 return start_end
@@ -67,9 +70,10 @@ class SimpleHistogram(Generic[T]):
             all_true = all_true and self.add_item(item)
         return all_true
 
-    def __repr__(self, *, width: int = 80, label_formatter: str = None) -> str:
+    def __repr__(self, *, width: int = 80, label_formatter: str = '%d') -> str:
         from text_utils import bar_graph
 
+        txt = ""
         max_population: Optional[int] = None
         for bucket in self.buckets:
             pop = self.buckets[bucket]
@@ -77,14 +81,12 @@ class SimpleHistogram(Generic[T]):
                 last_bucket_start = bucket[0]  # beginning of range
             if max_population is None or pop > max_population:
                 max_population = pop  # bucket with max items
-
-        txt = ""
         if max_population is None:
             return txt
 
-        max_label_width = None
-        lowest_start = None
-        highest_end = None
+        max_label_width: Optional[int] = None
+        lowest_start: int = None
+        highest_end: int = None
         for bucket in sorted(self.buckets, key=lambda x: x[0]):
             start = bucket[0]
             if lowest_start is None:
@@ -92,19 +94,16 @@ class SimpleHistogram(Generic[T]):
             end = bucket[1]
             if highest_end is None or end > highest_end:
                 highest_end = end
-            if label_formatter is None:
-                if type(start) == int and type(end) == int:
-                    label_formatter = '%d'
-                elif type(start) == float and type(end) == float:
-                    label_formatter = '%.2f'
-                else:
-                    label_formatter = '%s'
             label = f'[{label_formatter}..{label_formatter}): ' % (start, end)
             label_width = len(label)
             if max_label_width is None or label_width > max_label_width:
                 max_label_width = label_width
             if start == last_bucket_start:
                 break
+        assert max_label_width
+        assert lowest_start
+        assert highest_end
+
         sigma_label = f'[{label_formatter}..{label_formatter}): ' % (
             lowest_start,
             highest_end,
index 741e2a30dacd94306ac79a9c1cce4cc416b67e3f..0d07905be78daeb273995a0b5e131722e6e344d5 100644 (file)
@@ -6,7 +6,7 @@ from collections import defaultdict
 import logging
 import math
 import sys
-from typing import List, NamedTuple, Optional
+from typing import Dict, Generator, List, NamedTuple, Optional
 
 from ansi import fg, reset
 
@@ -22,10 +22,10 @@ class RowsColumns(NamedTuple):
 def get_console_rows_columns() -> RowsColumns:
     """Returns the number of rows/columns on the current console."""
 
-    from exec_utils import cmd_with_timeout
+    from exec_utils import cmd
 
     try:
-        rows, columns = cmd_with_timeout(
+        rows, columns = cmd(
             "stty size",
             timeout_seconds=1.0,
         ).split()
@@ -69,7 +69,7 @@ def bar_graph(
     reset=reset(),
     left_end="[",
     right_end="]",
-) -> None:
+) -> str:
     """Returns a string containing a bar graph.
 
     >>> bar_graph(0.5, fgcolor='', reset='')
@@ -217,8 +217,8 @@ def justify_text(text: str, *, width: int = 80, alignment: str = "c") -> str:
     return retval[1:]
 
 
-def generate_padded_columns(text: List[str]) -> str:
-    max_width = defaultdict(int)
+def generate_padded_columns(text: List[str]) -> Generator:
+    max_width: Dict[int, int] = defaultdict(int)
     for line in text:
         for pos, word in enumerate(line.split()):
             max_width[pos] = max(max_width[pos], len(word))