# HG changeset patch # User fschwarz # Date 1314794286 0 # Node ID 8831b754f81e01720eb2c6618b690b405b5e79d4 # Parent 4e561e6411ba04889f5450574d363cf96e8a775c Allow disabling cache behaviour in LazyProxy (fixes #208, initial patch Pedro Algarvio) diff --git a/ChangeLog b/ChangeLog --- a/ChangeLog +++ b/ChangeLog @@ -34,6 +34,8 @@ * Only use bankers round algorithm as a tie breaker if there are two nearest numbers, round as usual if there is only one nearest number (#267, patch by Martin) + * Allow disabling cache behaviour in LazyProxy (#208, initial patch Pedro + Algarvio) Version 0.9.6 diff --git a/babel/support.py b/babel/support.py --- a/babel/support.py +++ b/babel/support.py @@ -183,18 +183,22 @@ Hello, universe! Hello, world! """ - __slots__ = ['_func', '_args', '_kwargs', '_value'] + __slots__ = ['_func', '_args', '_kwargs', '_value', '_is_cache_enabled'] def __init__(self, func, *args, **kwargs): + is_cache_enabled = kwargs.pop('enable_cache', True) # Avoid triggering our own __setattr__ implementation object.__setattr__(self, '_func', func) object.__setattr__(self, '_args', args) object.__setattr__(self, '_kwargs', kwargs) + object.__setattr__(self, '_is_cache_enabled', is_cache_enabled) object.__setattr__(self, '_value', None) def value(self): if self._value is None: value = self._func(*self._args, **self._kwargs) + if not self._is_cache_enabled: + return value object.__setattr__(self, '_value', value) return self._value value = property(value) diff --git a/babel/tests/support.py b/babel/tests/support.py --- a/babel/tests/support.py +++ b/babel/tests/support.py @@ -163,10 +163,32 @@ 'VohsCTXD1', self.translations.ldnpgettext('messages1', 'foo', 'foo1', 'foos1', 2)) + +class LazyProxyTestCase(unittest.TestCase): + def test_proxy_caches_result_of_function_call(self): + self.counter = 0 + def add_one(): + self.counter += 1 + return self.counter + proxy = support.LazyProxy(add_one) + self.assertEqual(1, proxy.value) + self.assertEqual(1, proxy.value) + + def test_can_disable_proxy_cache(self): + self.counter = 0 + def add_one(): + self.counter += 1 + return self.counter + proxy = support.LazyProxy(add_one, enable_cache=False) + self.assertEqual(1, proxy.value) + self.assertEqual(2, proxy.value) + + def suite(): suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite(support)) suite.addTest(unittest.makeSuite(TranslationsTestCase, 'test')) + suite.addTest(unittest.makeSuite(LazyProxyTestCase, 'test')) return suite if __name__ == '__main__':