Skip to content

Commit

Permalink
LazyProxy: Handle AttributeError in specified func (#724)
Browse files Browse the repository at this point in the history
Fixes #723

Co-authored-by: Aarni Koskela <akx@iki.fi>
  • Loading branch information
nikifkon and akx committed Sep 30, 2020
1 parent e0e6aa6 commit 0444167
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
12 changes: 10 additions & 2 deletions babel/support.py
Expand Up @@ -165,7 +165,7 @@ class LazyProxy(object):
Hello, universe!
Hello, world!
"""
__slots__ = ['_func', '_args', '_kwargs', '_value', '_is_cache_enabled']
__slots__ = ['_func', '_args', '_kwargs', '_value', '_is_cache_enabled', '_attribute_error']

def __init__(self, func, *args, **kwargs):
is_cache_enabled = kwargs.pop('enable_cache', True)
Expand All @@ -175,11 +175,17 @@ def __init__(self, func, *args, **kwargs):
object.__setattr__(self, '_kwargs', kwargs)
object.__setattr__(self, '_is_cache_enabled', is_cache_enabled)
object.__setattr__(self, '_value', None)
object.__setattr__(self, '_attribute_error', None)

@property
def value(self):
if self._value is None:
value = self._func(*self._args, **self._kwargs)
try:
value = self._func(*self._args, **self._kwargs)
except AttributeError as error:
object.__setattr__(self, '_attribute_error', error)
raise

if not self._is_cache_enabled:
return value
object.__setattr__(self, '_value', value)
Expand Down Expand Up @@ -249,6 +255,8 @@ def __delattr__(self, name):
delattr(self.value, name)

def __getattr__(self, name):
if self._attribute_error is not None:
raise self._attribute_error
return getattr(self.value, name)

def __setattr__(self, name, value):
Expand Down
11 changes: 11 additions & 0 deletions tests/test_support.py
Expand Up @@ -279,6 +279,17 @@ def first(xs):
self.assertEqual(2, proxy.value)
self.assertEqual(1, proxy_deepcopy.value)

def test_handle_attribute_error(self):

def raise_attribute_error():
raise AttributeError('message')

proxy = support.LazyProxy(raise_attribute_error)
with pytest.raises(AttributeError) as exception:
proxy.value

self.assertEqual('message', str(exception.value))


def test_format_date():
fmt = support.Format('en_US')
Expand Down

0 comments on commit 0444167

Please sign in to comment.