From e6380bb1d74065769b13467d84a7342968f69095 Mon Sep 17 00:00:00 2001 From: Andrew Hamilton Date: Sun, 11 Jul 2021 16:41:06 +1000 Subject: [PATCH] Coding style. - Don't waste memory by storing sub-strings. --- eris/termstr.py | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/eris/termstr.py b/eris/termstr.py index f3c14f8..4f72998 100644 --- a/eris/termstr.py +++ b/eris/termstr.py @@ -220,17 +220,15 @@ class TermStr(collections.UserString): for index, style in enumerate(self.style): if style != last_style: if last_style is not None: - result.append( - (last_style, self.data[last_index:index], last_index)) + result.append((last_style, last_index, index)) last_style, last_index = style, index - result.append( - (last_style, self.data[last_index:len(self.style)], last_index)) + result.append((last_style, last_index, len(self.style))) return result def __str__(self): return "".join(_join_lists( - [style.code_for_term, str_] - for style, str_, position in self._partition_style) + + [style.code_for_term, self.data[start_index:end_index]] + for style, start_index, end_index in self._partition_style) + [terminal.ESC + terminal.normal]) def __repr__(self): @@ -314,9 +312,9 @@ class TermStr(collections.UserString): # Below are extra methods useful for termstrs. def transform_style(self, transform_func): - new_style = tuple(_join_lists([transform_func(style)] * len(str_) - for style, str_, position - in self._partition_style)) + new_style = tuple(_join_lists( + [transform_func(style)] * (end_index - start_index) + for style, start_index, end_index in self._partition_style)) return self.__class__(self.data, new_style) def bold(self): @@ -357,9 +355,9 @@ class TermStr(collections.UserString): def as_html(self): result = [] styles = set() - for style, str_, position in self._partition_style: + for style, start_index, end_index in self._partition_style: styles.add(style) - encoded = str(html.escape(str_).encode( + encoded = str(html.escape(self.data[start_index:end_index]).encode( "ascii", "xmlcharrefreplace"))[2:-1] encoded = encoded.replace("\\\\", "\\") result.append(f'{encoded}')