X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=text_utils.py;h=720bf20561a63bcd5c1afeba42658c8924566adc;hb=f2600f30801c849fc1d139386e3ddc3c9eb43e30;hp=76cc7e816db9ae87581989bc314fd7d07d4ca154;hpb=a3eb24ea374a7f231e595c1a6e2c8e49d482c594;p=python_utils.git diff --git a/text_utils.py b/text_utils.py index 76cc7e8..720bf20 100644 --- a/text_utils.py +++ b/text_utils.py @@ -3,20 +3,25 @@ """Utilities for dealing with "text".""" +import contextlib import logging import math import sys from collections import defaultdict -from typing import Dict, Generator, List, NamedTuple, Optional, Tuple +from dataclasses import dataclass +from typing import Dict, Generator, List, Literal, Optional, Tuple from ansi import fg, reset logger = logging.getLogger(__file__) -class RowsColumns(NamedTuple): - rows: int - columns: int +@dataclass +class RowsColumns: + """Row + Column""" + + rows: int = 0 + columns: int = 0 def get_console_rows_columns() -> RowsColumns: @@ -31,7 +36,7 @@ def get_console_rows_columns() -> RowsColumns: ).split() except Exception as e: logger.exception(e) - raise Exception('Can\'t determine console size?!') + raise Exception('Can\'t determine console size?!') from e return RowsColumns(int(rows), int(columns)) @@ -122,10 +127,10 @@ def sparkline(numbers: List[float]) -> Tuple[float, float, str]: barcount = len(_bar) min_num, max_num = min(numbers), max(numbers) span = max_num - min_num - sparkline = ''.join( + sline = ''.join( _bar[min([barcount - 1, int((n - min_num) / span * barcount)])] for n in numbers ) - return min_num, max_num, sparkline + return min_num, max_num, sline def distribute_strings( @@ -259,7 +264,7 @@ def wrap_string(text: str, n: int) -> str: return out -class Indenter(object): +class Indenter(contextlib.AbstractContextManager): """ with Indenter(pad_count = 8) as i: i.print('test') @@ -287,10 +292,11 @@ class Indenter(object): self.level += 1 return self - def __exit__(self, exc_type, exc_value, exc_tb): + def __exit__(self, exc_type, exc_value, exc_tb) -> Literal[False]: self.level -= 1 if self.level < -1: self.level = -1 + return False def print(self, *arg, **kwargs): import string_utils