forked from faif/python-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
delegation_pattern.py
57 lines (41 loc) · 1.25 KB
/
delegation_pattern.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
"""
Reference: https://en.wikipedia.org/wiki/Delegation_pattern
Author: https://github.com/IuryAlves
*TL;DR
Allows object composition to achieve the same code reuse as inheritance.
"""
from __future__ import annotations
from typing import Any, Callable, Union
class Delegator:
"""
>>> delegator = Delegator(Delegate())
>>> delegator.p1
123
>>> delegator.p2
Traceback (most recent call last):
...
AttributeError: 'Delegate' object has no attribute 'p2'
>>> delegator.do_something("nothing")
'Doing nothing'
>>> delegator.do_anything()
Traceback (most recent call last):
...
AttributeError: 'Delegate' object has no attribute 'do_anything'
"""
def __init__(self, delegate: Delegate):
self.delegate = delegate
def __getattr__(self, name: str) -> Union[Any, Callable]:
attr = getattr(self.delegate, name)
if not callable(attr):
return attr
def wrapper(*args, **kwargs):
return attr(*args, **kwargs)
return wrapper
class Delegate:
def __init__(self):
self.p1 = 123
def do_something(self, something: str) -> str:
return f"Doing {something}"
if __name__ == "__main__":
import doctest
doctest.testmod()