From d72af90b998f5cee4d138aea39a0d6f5a8d3d3b3 Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Wed, 10 Sep 2025 13:15:37 +0300 Subject: [PATCH] Use faster generator for link IDs --- rich/style.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/rich/style.py b/rich/style.py index 529424189..ba953f4b5 100644 --- a/rich/style.py +++ b/rich/style.py @@ -1,8 +1,9 @@ import sys from functools import lru_cache +from itertools import count from operator import attrgetter from pickle import dumps, loads -from random import randint +from time import time from typing import Any, Dict, Iterable, List, Optional, Type, Union, cast from . import errors @@ -18,6 +19,9 @@ StyleType = Union[str, "Style"] +_id_generator = count(int(time()) >> 4) + + class _Bit: """A descriptor to get/set a style attribute bit.""" @@ -195,7 +199,7 @@ def _make_color(color: Union[Color, str]) -> Color: self._link = link self._meta = None if meta is None else dumps(meta) self._link_id = ( - f"{randint(0, 999999)}{hash(self._meta)}" if (link or meta) else "" + f"{next(_id_generator)}{hash(self._meta)}" if (link or meta) else "" ) self._hash: Optional[int] = None self._null = not (self._set_attributes or color or bgcolor or link or meta) @@ -245,7 +249,7 @@ def from_meta(cls, meta: Optional[Dict[str, Any]]) -> "Style": style._attributes = 0 style._link = None style._meta = dumps(meta) - style._link_id = f"{randint(0, 999999)}{hash(style._meta)}" + style._link_id = f"{next(_id_generator)}{hash(style._meta)}" style._hash = None style._null = not (meta) return style @@ -483,7 +487,7 @@ def without_color(self) -> "Style": style._attributes = self._attributes style._set_attributes = self._set_attributes style._link = self._link - style._link_id = f"{randint(0, 999999)}" if self._link else "" + style._link_id = f"{next(_id_generator)}" if self._link else "" style._null = False style._meta = None style._hash = None @@ -635,7 +639,7 @@ def copy(self) -> "Style": style._attributes = self._attributes style._set_attributes = self._set_attributes style._link = self._link - style._link_id = f"{randint(0, 999999)}" if self._link else "" + style._link_id = f"{next(_id_generator)}" if self._link else "" style._hash = self._hash style._null = False style._meta = self._meta @@ -681,7 +685,7 @@ def update_link(self, link: Optional[str] = None) -> "Style": style._attributes = self._attributes style._set_attributes = self._set_attributes style._link = link - style._link_id = f"{randint(0, 999999)}" if link else "" + style._link_id = f"{next(_id_generator)}" if link else "" style._hash = None style._null = False style._meta = self._meta