Skip to content

Commit f38a8d2

Browse files
authored
Merge pull request #332 from rednafi/master
Type checked adapter pattern
2 parents a2ad441 + 44ce0a5 commit f38a8d2

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

patterns/structural/adapter.py

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -28,58 +28,63 @@
2828
Allows the interface of an existing class to be used as another interface.
2929
"""
3030

31+
from typing import Callable, TypeVar
32+
33+
T = TypeVar("T")
34+
3135

3236
class Dog:
33-
def __init__(self):
37+
def __init__(self) -> None:
3438
self.name = "Dog"
3539

36-
def bark(self):
40+
def bark(self) -> str:
3741
return "woof!"
3842

3943

4044
class Cat:
41-
def __init__(self):
45+
def __init__(self) -> None:
4246
self.name = "Cat"
4347

44-
def meow(self):
48+
def meow(self) -> str:
4549
return "meow!"
4650

4751

4852
class Human:
49-
def __init__(self):
53+
def __init__(self) -> None:
5054
self.name = "Human"
5155

52-
def speak(self):
56+
def speak(self) -> str:
5357
return "'hello'"
5458

5559

5660
class Car:
57-
def __init__(self):
61+
def __init__(self) -> None:
5862
self.name = "Car"
5963

60-
def make_noise(self, octane_level):
61-
return "vroom{0}".format("!" * octane_level)
64+
def make_noise(self, octane_level: int) -> str:
65+
return f"vroom{'!' * octane_level}"
6266

6367

6468
class Adapter:
65-
"""
66-
Adapts an object by replacing methods.
67-
Usage:
69+
"""Adapts an object by replacing methods.
70+
71+
Usage
72+
------
6873
dog = Dog()
6974
dog = Adapter(dog, make_noise=dog.bark)
7075
"""
7176

72-
def __init__(self, obj, **adapted_methods):
73-
"""We set the adapted methods in the object's dict"""
77+
def __init__(self, obj: T, **adapted_methods: Callable):
78+
"""We set the adapted methods in the object's dict."""
7479
self.obj = obj
7580
self.__dict__.update(adapted_methods)
7681

7782
def __getattr__(self, attr):
78-
"""All non-adapted calls are passed to the object"""
83+
"""All non-adapted calls are passed to the object."""
7984
return getattr(self.obj, attr)
8085

8186
def original_dict(self):
82-
"""Print original object dict"""
87+
"""Print original object dict."""
8388
return self.obj.__dict__
8489

8590

@@ -116,4 +121,5 @@ def main():
116121

117122
if __name__ == "__main__":
118123
import doctest
124+
119125
doctest.testmod(optionflags=doctest.ELLIPSIS)

0 commit comments

Comments
 (0)