Skip to content

Commit 09e0bff

Browse files
Add caching to warn_print (#1276)
1 parent a69a1f3 commit 09e0bff

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

src/usethis/_console.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import codecs
4+
import functools
45
import sys
56
from typing import TYPE_CHECKING
67

@@ -97,5 +98,10 @@ def err_print(msg: str | Exception) -> None:
9798
def warn_print(msg: str | Exception) -> None:
9899
msg = str(msg)
99100

101+
_cached_warn_print(msg)
102+
103+
104+
@functools.cache
105+
def _cached_warn_print(msg: str) -> None:
100106
if not usethis_config.quiet:
101107
console.print(f"⚠ {msg}", style="yellow")

tests/conftest.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,26 @@
77
import pytest
88

99
from usethis._config import usethis_config
10+
from usethis._console import _cached_warn_print
1011
from usethis._integrations.backend.uv.call import call_subprocess, call_uv_subprocess
1112
from usethis._integrations.file.pyproject_toml.io_ import PyprojectTOMLManager
1213
from usethis._test import change_cwd, is_offline
14+
from usethis._tool.impl.import_linter import _importlinter_warn_no_packages_found
1315

1416
if "UV_PYTHON" in os.environ:
1517
# To allow test subprocesses to use different versions of Python than the one
1618
# running the tests.
1719
del os.environ["UV_PYTHON"]
1820

1921

22+
@pytest.fixture(autouse=True)
23+
def clear_functools_caches():
24+
"""Fixture to clear functools.caches before each test."""
25+
26+
_cached_warn_print.cache_clear()
27+
_importlinter_warn_no_packages_found.cache_clear()
28+
29+
2030
@pytest.fixture(scope="session")
2131
def _uv_init_dir(tmp_path_factory: pytest.TempPathFactory) -> Path:
2232
tmp_path = tmp_path_factory.mktemp("uv_init")

tests/usethis/test_console.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,3 +166,23 @@ def test_alert_only_doesnt_suppress(
166166
out, err = capfd.readouterr()
167167
assert not err
168168
assert out == "⚠ Hello\n"
169+
170+
def test_cached_str(self, capfd: pytest.CaptureFixture[str]) -> None:
171+
# Act
172+
warn_print("Hello")
173+
warn_print("Hello")
174+
175+
# Assert
176+
out, err = capfd.readouterr()
177+
assert not err
178+
assert out == "⚠ Hello\n"
179+
180+
def test_cached_exception(self, capfd: pytest.CaptureFixture[str]) -> None:
181+
# Act
182+
warn_print(Exception("Hello"))
183+
warn_print(Exception("Hello"))
184+
185+
# Assert
186+
out, err = capfd.readouterr()
187+
assert not err
188+
assert out == "⚠ Hello\n"

0 commit comments

Comments
 (0)