-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorator.py
More file actions
55 lines (38 loc) · 1.06 KB
/
decorator.py
File metadata and controls
55 lines (38 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from typing import Callable, Dict
import functools
def fibo(n: int) -> int:
if n == 1:
return 1
if n == 2:
return 1
return fibo(n - 1) + fibo(n - 2)
# as function
def memorize(f: Callable[[int], int]) -> Callable[[int], int]:
memory: Dict[int, int] = dict()
@functools.wraps(f)
def wrapper(arg: int) -> int:
if arg not in memory:
memory[arg] = f(arg)
return memory[arg]
return wrapper
# as class
class Memorize:
def __init__(self, f: Callable[[int], int]):
self.function = f
self.memory: Dict[int, int] = dict()
functools.update_wrapper(self, f)
def __call__(self, arg: int) -> int:
if arg not in self.memory:
self.memory[arg] = self.function(arg)
return self.memory[arg]
ff = memorize(fibo)
fc = Memorize(fibo)
print(f"{ff(10)} as function and {fc(10)} as class")
class Fake:
def __init__(self, function):
self.function = function
@Fake
def to_nil(n: int) -> int:
return n
print(type(to_nil))
print(to_nil.function(10))