Skip to content
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
6 changes: 5 additions & 1 deletion babel/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ class LazyProxy:
'_kwargs',
'_value',
'_is_cache_enabled',
'_is_cached',
'_attribute_error',
]

Expand All @@ -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

Expand All @@ -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:
Expand All @@ -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:
Expand Down
18 changes: 18 additions & 0 deletions tests/test_support_lazy_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
[
Expand Down