Skip to content

Instantly share code, notes, and snippets.

@hp0404
Created April 27, 2022 08:11
Show Gist options
  • Select an option

  • Save hp0404/e79cf3c13c7737684eedf755a7081645 to your computer and use it in GitHub Desktop.

Select an option

Save hp0404/e79cf3c13c7737684eedf755a7081645 to your computer and use it in GitHub Desktop.
Короткий приклад декоратора з параметрами
import functools
def pop_item(di, *, first=True):
if first:
it = iter(di)
else:
it = iter(reversed(di))
key = next(it)
return key, di.pop(key)
def cached(param=None, *, maxsize=None):
def _cached(func):
data = {}
@functools.wraps(func)
def _cached_inner(*args):
if args in data:
return data[args]
else:
if maxsize is not None and len(data) >= maxsize:
pop_item(data, first=True)
data[args] = ret = func(*args)
return ret
return _cached_inner
return _cached(param) if param else _cached
#@cached
@cached(maxsize=3)
def add(x: int, y: int) -> int:
return x + y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment