-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_dispatch.py
61 lines (38 loc) · 1.16 KB
/
my_dispatch.py
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
56
57
58
59
60
61
from collections import defaultdict
dispatch_map = defaultdict(dict)
def register_dispatch(dispatch_func, kind, func):
kind_map = dispatch_map[dispatch_func]
kind_map[kind] = func
def call_dispatch(dispatch_func, value, *args, **kwargs):
kind_map = dispatch_map[dispatch_func]
for kind in type(value).__mro__:
if kind in kind_map:
func = kind_map[kind]
return func(value, *args, **kwargs)
return dispatch_func(value, *args, **kwargs)
from functools import wraps
def my_dispatch(dispatch_func):
@wraps(dispatch_func)
def inner(*args, **kwargs):
return call_dispatch(dispatch_func, *args, **kwargs)
setattr(inner, "register", register_helper(dispatch_func))
return inner
def register_helper(dispatch_func):
def outer(kind):
def decorator(func):
register_dispatch(dispatch_func, kind, func)
return func
return decorator
return outer
@my_dispatch
def my_print(value):
print(f"Default implementation: {value}")
@my_print.register(int)
def _(value):
print(f"Integer print: {value}")
@my_print.register(float)
def _(value):
print(f"Float print: {value}")
my_print(5)
my_print(1.23)
my_print("unknown")