Skip to content

Commit ce2c40f

Browse files
authored
Merge pull request faif#326 from rednafi/master
Added type hints to delegation pattern
2 parents 697deba + 8894264 commit ce2c40f

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

patterns/fundamental/delegation_pattern.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
Allows object composition to achieve the same code reuse as inheritance.
77
"""
88

9+
from __future__ import annotations
10+
from typing import Any, Callable, Union
11+
912

1013
class Delegator:
1114
"""
@@ -24,29 +27,30 @@ class Delegator:
2427
AttributeError: 'Delegate' object has no attribute 'do_anything'
2528
"""
2629

27-
def __init__(self, delegate):
30+
def __init__(self, delegate: Delegate):
2831
self.delegate = delegate
2932

30-
def __getattr__(self, name):
33+
def __getattr__(self, name: str) -> Union[Any, Callable]:
3134
attr = getattr(self.delegate, name)
3235

3336
if not callable(attr):
3437
return attr
3538

3639
def wrapper(*args, **kwargs):
3740
return attr(*args, **kwargs)
41+
3842
return wrapper
3943

4044

4145
class Delegate:
4246
def __init__(self):
4347
self.p1 = 123
4448

45-
def do_something(self, something):
46-
return "Doing %s" % something
49+
def do_something(self, something: str) -> str:
50+
return f"Doing {something}"
4751

4852

49-
if __name__ == '__main__':
53+
if __name__ == "__main__":
5054
import doctest
5155

5256
doctest.testmod()

0 commit comments

Comments
 (0)