From 3a3b71143826cf34a6b5a37b2cffe82928c54a1c Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Tue, 2 Jul 2024 08:34:54 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20up=20JupyterRender?= =?UTF-8?q?able.=5Frepr=5Fmimebundle=5F()=20by=2011%=20To=20optimize=20the?= =?UTF-8?q?=20original=20program=20for=20both=20time=20and=20memory,=20we?= =?UTF-8?q?=20can=20make=20several=20improvements.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Use generator expressions instead of dictionary comprehensions when iterating through items conditionally. 2. Implement early returns to avoid unnecessary computation. #### Improvements made. 1. **Conditionally Filter Early**: The include filtering is done before the exclude filtering to reduce the size of the dictionary as soon as possible. 2. **Early Return**: If there are no `exclude` items after filtering by `include`, the function returns early to save on further unnecessary processing. 3. **Avoid Unnecessary Iterations**: Checking conditions before performing operations minimizes redundant computations. --- rich/jupyter.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/rich/jupyter.py b/rich/jupyter.py index 24135a9f7..275fd2f96 100644 --- a/rich/jupyter.py +++ b/rich/jupyter.py @@ -26,10 +26,18 @@ def _repr_mimebundle_( self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any ) -> Dict[str, str]: data = {"text/plain": self.text, "text/html": self.html} + + # Check if we need to filter by include if include: - data = {k: v for (k, v) in data.items() if k in include} + data = {k: data[k] for k in data if k in include} + # Early return if there's nothing to exclude + if not exclude: + return data + + # Check if we need to filter by exclude if exclude: - data = {k: v for (k, v) in data.items() if k not in exclude} + data = {k: data[k] for k in data if k not in exclude} + return data