From d9ed9f8a9e54f93ef3e524c541e085ea615726af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9B=BE=E6=A5=9A=E7=AC=91?= Date: Wed, 23 Sep 2026 00:43:40 +0800 Subject: [PATCH] Cache None results in LazyProxy --- babel/support.py | 6 +++++- tests/test_support_lazy_proxy.py | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/babel/support.py b/babel/support.py index 8cc2492e8..93e8fa910 100644 --- a/babel/support.py +++ b/babel/support.py @@ -289,6 +289,7 @@ class LazyProxy: '_kwargs', '_value', '_is_cache_enabled', + '_is_cached', '_attribute_error', ] @@ -297,6 +298,7 @@ class LazyProxy: _args: tuple[Any, ...] _kwargs: dict[str, Any] _is_cache_enabled: bool + _is_cached: bool _value: Any _attribute_error: AttributeError | None @@ -312,12 +314,13 @@ def __init__( object.__setattr__(self, '_args', args) object.__setattr__(self, '_kwargs', kwargs) object.__setattr__(self, '_is_cache_enabled', enable_cache) + object.__setattr__(self, '_is_cached', False) object.__setattr__(self, '_value', None) object.__setattr__(self, '_attribute_error', None) @property def value(self) -> Any: - if self._value is None: + if not self._is_cached: try: value = self._func(*self._args, **self._kwargs) except AttributeError as error: @@ -327,6 +330,7 @@ def value(self) -> Any: if not self._is_cache_enabled: return value object.__setattr__(self, '_value', value) + object.__setattr__(self, '_is_cached', True) return self._value def __contains__(self, key: object) -> bool: diff --git a/tests/test_support_lazy_proxy.py b/tests/test_support_lazy_proxy.py index 59cab1f58..3ce016706 100644 --- a/tests/test_support_lazy_proxy.py +++ b/tests/test_support_lazy_proxy.py @@ -31,6 +31,24 @@ def add_one(): assert proxy.value == 2 +@pytest.mark.parametrize('value', [None, False, 0, '', []]) +@pytest.mark.parametrize('enable_cache', [True, False]) +def test_proxy_caches_falsey_values(value, enable_cache): + calls = 0 + + def get_value(): + nonlocal calls + calls += 1 + return value + + proxy = support.LazyProxy(get_value, enable_cache=enable_cache) + assert calls == 0 + assert proxy.value is value + assert proxy.value is value + assert not proxy + assert calls == (1 if enable_cache else 3) + + @pytest.mark.parametrize( ("copier", "expected_copy_value"), [