Created
April 27, 2022 08:11
-
-
Save hp0404/e79cf3c13c7737684eedf755a7081645 to your computer and use it in GitHub Desktop.
Короткий приклад декоратора з параметрами
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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