def test_unhashable(): '''Test `SleekCallArgs` on unhashable arguments.''' sca_dict = {} args = ([1, 2], {1: [1, 2]}, set(('a', 1))) sca1 = SleekCallArgs(sca_dict, f, *args) hash(sca1) sca_dict[sca1] = 'meow' del args gc_tools.collect() # GCed because there's a `set` in `args`, and it's weakreffable: assert len(sca_dict) == 0 kwargs = { 'a': {1: 2}, 'b': [ set(), set((frozenset((3, 4)))) ] } sca2 = SleekCallArgs(sca_dict, f, **kwargs) hash(sca2) sca_dict[sca2] = 'meow' del kwargs gc_tools.collect() # Not GCed because all objects in `kwargs` are not weakreffable: assert len(sca_dict) == 1
def test(): '''Test the basic workings of `SleekCallArgs`.''' sca_dict = {} args = (1, 2) sca1 = SleekCallArgs(sca_dict, f, *args) sca_dict[sca1] = 'meow' del args gc_tools.collect() assert len(sca_dict) == 1 args = (1, A()) sca2 = SleekCallArgs(sca_dict, f, *args) sca_dict[sca2] = 'meow' del args gc_tools.collect() assert len(sca_dict) == 1
def cached(function, *args, **kwargs): sleek_call_args = \ SleekCallArgs(cached._cache, function, *args, **kwargs) try: return cached._cache[sleek_call_args] except KeyError: cached._cache[sleek_call_args] = value = \ function(*args, **kwargs) return value
def __call__(cls, *args, **kwargs): sleek_call_args = SleekCallArgs(cls.__cache, cls.__init__, *((SelfPlaceholder, ) + args), **kwargs) try: return cls.__cache[sleek_call_args] except KeyError: cls.__cache[sleek_call_args] = value = \ super().__call__(*args, **kwargs) return value
def cached(function, *args, **kwargs): remove_expired_entries() sleek_call_args = \ SleekCallArgs(cached._cache, function, *args, **kwargs) try: return cached._cache[sleek_call_args][0] except KeyError: value = function(*args, **kwargs) cached._cache[sleek_call_args] = (value, _get_now() + time_to_keep) cached._cache.sort(key=sorting_key_function) return value
def cached(function, *args, **kwargs): sleek_call_args = \ SleekCallArgs(cached._cache, function, *args, **kwargs) try: result = cached._cache[sleek_call_args] cached._cache.move_to_end(sleek_call_args) return result except KeyError: cached._cache[sleek_call_args] = value = \ function(*args, **kwargs) if len(cached._cache) > max_size: cached._cache.popitem(last=False) return value