Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Style link id cache #3136

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions rich/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -729,8 +729,7 @@ def test(self, text: Optional[str] = None) -> None:
text = text or str(self)
sys.stdout.write(f"{self.render(text)}\n")

@lru_cache(maxsize=1024)
def _add(self, style: Optional["Style"]) -> "Style":
def _add_no_cache(self, style: Optional["Style"]) -> "Style":
if style is None or style._null:
return self
if self._null:
Expand All @@ -754,8 +753,20 @@ def _add(self, style: Optional["Style"]) -> "Style":
new_style._hash = None
return new_style

@lru_cache(maxsize=1024)
def _add(self, style: Optional["Style"]) -> "Style":
return self._add_no_cache(style)

def __add__(self, style: Optional["Style"]) -> "Style":
combined_style = self._add(style)
if (
style is not None
and not style._link
and not self._link
and (self._link_id or style._link_id)
):
combined_style = self._add_no_cache(style)
else:
combined_style = self._add(style)
return combined_style.copy() if combined_style.link else combined_style


Expand Down
9 changes: 5 additions & 4 deletions rich/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,18 +746,19 @@ def render(self, console: "Console", end: str = "") -> Iterable["Segment"]:
stack_append = stack.append
stack_pop = stack.remove

style_cache: Dict[Tuple[Style, ...], Style] = {}
style_cache: Dict[Tuple[int, ...], Style] = {}
style_cache_get = style_cache.get
combine = Style.combine

def get_current_style() -> Style:
"""Construct current style from stack."""
styles = tuple(style_map[_style_id] for _style_id in sorted(stack))
cached_style = style_cache_get(styles)
cache_key = tuple(sorted(stack))
cached_style = style_cache_get(cache_key)
if cached_style is not None:
return cached_style
styles = tuple(style_map[_style_id] for _style_id in sorted(stack))
current_style = combine(styles)
style_cache[styles] = current_style
style_cache[cache_key] = current_style
return current_style

for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]):
Expand Down