Skip to content

Commit 9d4170d

Browse files
committed
issue 373: add more type hints
1 parent be59b53 commit 9d4170d

File tree

9 files changed

+75
-65
lines changed

9 files changed

+75
-65
lines changed

patterns/behavioral/publish_subscribe.py

+14-11
Original file line numberDiff line numberDiff line change
@@ -5,47 +5,50 @@
55
"""
66

77

8+
from __future__ import annotations
9+
10+
811
class Provider:
9-
def __init__(self):
12+
def __init__(self) -> None:
1013
self.msg_queue = []
1114
self.subscribers = {}
1215

13-
def notify(self, msg):
16+
def notify(self, msg: str) -> None:
1417
self.msg_queue.append(msg)
1518

16-
def subscribe(self, msg, subscriber):
19+
def subscribe(self, msg: str, subscriber: Subscriber) -> None:
1720
self.subscribers.setdefault(msg, []).append(subscriber)
1821

19-
def unsubscribe(self, msg, subscriber):
22+
def unsubscribe(self, msg: str, subscriber: Subscriber) -> None:
2023
self.subscribers[msg].remove(subscriber)
2124

22-
def update(self):
25+
def update(self) -> None:
2326
for msg in self.msg_queue:
2427
for sub in self.subscribers.get(msg, []):
2528
sub.run(msg)
2629
self.msg_queue = []
2730

2831

2932
class Publisher:
30-
def __init__(self, msg_center):
33+
def __init__(self, msg_center: Provider) -> None:
3134
self.provider = msg_center
3235

33-
def publish(self, msg):
36+
def publish(self, msg: str) -> None:
3437
self.provider.notify(msg)
3538

3639

3740
class Subscriber:
38-
def __init__(self, name, msg_center):
41+
def __init__(self, name: str, msg_center: Provider) -> None:
3942
self.name = name
4043
self.provider = msg_center
4144

42-
def subscribe(self, msg):
45+
def subscribe(self, msg: str) -> None:
4346
self.provider.subscribe(msg, self)
4447

45-
def unsubscribe(self, msg):
48+
def unsubscribe(self, msg: str) -> None:
4649
self.provider.unsubscribe(msg, self)
4750

48-
def run(self, msg):
51+
def run(self, msg: str) -> None:
4952
print(f"{self.name} got {msg}")
5053

5154

patterns/behavioral/state.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@
88
Implements state transitions by invoking methods from the pattern's superclass.
99
"""
1010

11+
from __future__ import annotations
1112

12-
class State:
1313

14+
class State:
1415
"""Base state. This is to share functionality"""
1516

16-
def scan(self):
17+
def scan(self) -> None:
1718
"""Scan the dial to the next station"""
1819
self.pos += 1
1920
if self.pos == len(self.stations):
@@ -22,43 +23,42 @@ def scan(self):
2223

2324

2425
class AmState(State):
25-
def __init__(self, radio):
26+
def __init__(self, radio: Radio) -> None:
2627
self.radio = radio
2728
self.stations = ["1250", "1380", "1510"]
2829
self.pos = 0
2930
self.name = "AM"
3031

31-
def toggle_amfm(self):
32+
def toggle_amfm(self) -> None:
3233
print("Switching to FM")
3334
self.radio.state = self.radio.fmstate
3435

3536

3637
class FmState(State):
37-
def __init__(self, radio):
38+
def __init__(self, radio: Radio) -> None:
3839
self.radio = radio
3940
self.stations = ["81.3", "89.1", "103.9"]
4041
self.pos = 0
4142
self.name = "FM"
4243

43-
def toggle_amfm(self):
44+
def toggle_amfm(self) -> None:
4445
print("Switching to AM")
4546
self.radio.state = self.radio.amstate
4647

4748

4849
class Radio:
49-
5050
"""A radio. It has a scan button, and an AM/FM toggle switch."""
5151

52-
def __init__(self):
52+
def __init__(self) -> None:
5353
"""We have an AM state and an FM state"""
5454
self.amstate = AmState(self)
5555
self.fmstate = FmState(self)
5656
self.state = self.amstate
5757

58-
def toggle_amfm(self):
58+
def toggle_amfm(self) -> None:
5959
self.state.toggle_amfm()
6060

61-
def scan(self):
61+
def scan(self) -> None:
6262
self.state.scan()
6363

6464

patterns/creational/borg.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,12 @@
3838
class Borg:
3939
_shared_state: Dict[str, str] = {}
4040

41-
def __init__(self):
41+
def __init__(self) -> None:
4242
self.__dict__ = self._shared_state
4343

4444

4545
class YourBorg(Borg):
46-
def __init__(self, state=None):
46+
def __init__(self, state: str = None) -> None:
4747
super().__init__()
4848
if state:
4949
self.state = state
@@ -52,7 +52,7 @@ def __init__(self, state=None):
5252
if not hasattr(self, "state"):
5353
self.state = "Init"
5454

55-
def __str__(self):
55+
def __str__(self) -> str:
5656
return self.state
5757

5858

patterns/creational/builder.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class for a building, where the initializer (__init__ method) specifies the
3434

3535
# Abstract Building
3636
class Building:
37-
def __init__(self):
37+
def __init__(self) -> None:
3838
self.build_floor()
3939
self.build_size()
4040

@@ -44,24 +44,24 @@ def build_floor(self):
4444
def build_size(self):
4545
raise NotImplementedError
4646

47-
def __repr__(self):
47+
def __repr__(self) -> str:
4848
return "Floor: {0.floor} | Size: {0.size}".format(self)
4949

5050

5151
# Concrete Buildings
5252
class House(Building):
53-
def build_floor(self):
53+
def build_floor(self) -> None:
5454
self.floor = "One"
5555

56-
def build_size(self):
56+
def build_size(self) -> None:
5757
self.size = "Big"
5858

5959

6060
class Flat(Building):
61-
def build_floor(self):
61+
def build_floor(self) -> None:
6262
self.floor = "More than One"
6363

64-
def build_size(self):
64+
def build_size(self) -> None:
6565
self.size = "Small"
6666

6767

@@ -72,19 +72,19 @@ def build_size(self):
7272

7373

7474
class ComplexBuilding:
75-
def __repr__(self):
75+
def __repr__(self) -> str:
7676
return "Floor: {0.floor} | Size: {0.size}".format(self)
7777

7878

7979
class ComplexHouse(ComplexBuilding):
80-
def build_floor(self):
80+
def build_floor(self) -> None:
8181
self.floor = "One"
8282

83-
def build_size(self):
83+
def build_size(self) -> None:
8484
self.size = "Big and fancy"
8585

8686

87-
def construct_building(cls):
87+
def construct_building(cls) -> Building:
8888
building = cls()
8989
building.build_floor()
9090
building.build_size()

patterns/fundamental/delegation_pattern.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ class Delegator:
2828
AttributeError: 'Delegate' object has no attribute 'do_anything'
2929
"""
3030

31-
def __init__(self, delegate: Delegate):
31+
def __init__(self, delegate: Delegate) -> None:
3232
self.delegate = delegate
3333

3434
def __getattr__(self, name: str) -> Any | Callable:
@@ -44,7 +44,7 @@ def wrapper(*args, **kwargs):
4444

4545

4646
class Delegate:
47-
def __init__(self):
47+
def __init__(self) -> None:
4848
self.p1 = 123
4949

5050
def do_something(self, something: str) -> str:

patterns/other/blackboard.py

+15-12
Original file line numberDiff line numberDiff line change
@@ -8,30 +8,33 @@
88
99
https://en.wikipedia.org/wiki/Blackboard_system
1010
"""
11+
from __future__ import annotations
1112

1213
import abc
1314
import random
1415

16+
from typing import List
17+
1518

1619
class Blackboard:
17-
def __init__(self):
18-
self.experts = []
20+
def __init__(self) -> None:
21+
self.experts: List = []
1922
self.common_state = {
2023
"problems": 0,
2124
"suggestions": 0,
2225
"contributions": [],
2326
"progress": 0, # percentage, if 100 -> task is finished
2427
}
2528

26-
def add_expert(self, expert):
29+
def add_expert(self, expert: AbstractExpert) -> None:
2730
self.experts.append(expert)
2831

2932

3033
class Controller:
31-
def __init__(self, blackboard):
34+
def __init__(self, blackboard: Blackboard) -> None:
3235
self.blackboard = blackboard
3336

34-
def run_loop(self):
37+
def run_loop(self) -> List[str]:
3538
"""
3639
This function is a loop that runs until the progress reaches 100.
3740
It checks if an expert is eager to contribute and then calls its contribute method.
@@ -44,7 +47,7 @@ def run_loop(self):
4447

4548

4649
class AbstractExpert(metaclass=abc.ABCMeta):
47-
def __init__(self, blackboard):
50+
def __init__(self, blackboard: Blackboard) -> None:
4851
self.blackboard = blackboard
4952

5053
@property
@@ -59,10 +62,10 @@ def contribute(self):
5962

6063
class Student(AbstractExpert):
6164
@property
62-
def is_eager_to_contribute(self):
65+
def is_eager_to_contribute(self) -> bool:
6366
return True
6467

65-
def contribute(self):
68+
def contribute(self) -> None:
6669
self.blackboard.common_state["problems"] += random.randint(1, 10)
6770
self.blackboard.common_state["suggestions"] += random.randint(1, 10)
6871
self.blackboard.common_state["contributions"] += [self.__class__.__name__]
@@ -71,10 +74,10 @@ def contribute(self):
7174

7275
class Scientist(AbstractExpert):
7376
@property
74-
def is_eager_to_contribute(self):
77+
def is_eager_to_contribute(self) -> int:
7578
return random.randint(0, 1)
7679

77-
def contribute(self):
80+
def contribute(self) -> None:
7881
self.blackboard.common_state["problems"] += random.randint(10, 20)
7982
self.blackboard.common_state["suggestions"] += random.randint(10, 20)
8083
self.blackboard.common_state["contributions"] += [self.__class__.__name__]
@@ -83,10 +86,10 @@ def contribute(self):
8386

8487
class Professor(AbstractExpert):
8588
@property
86-
def is_eager_to_contribute(self):
89+
def is_eager_to_contribute(self) -> bool:
8790
return True if self.blackboard.common_state["problems"] > 100 else False
8891

89-
def contribute(self):
92+
def contribute(self) -> None:
9093
self.blackboard.common_state["problems"] += random.randint(1, 2)
9194
self.blackboard.common_state["suggestions"] += random.randint(10, 20)
9295
self.blackboard.common_state["contributions"] += [self.__class__.__name__]

patterns/structural/decorator.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -28,30 +28,30 @@
2828
class TextTag:
2929
"""Represents a base text tag"""
3030

31-
def __init__(self, text):
31+
def __init__(self, text: str) -> None:
3232
self._text = text
3333

34-
def render(self):
34+
def render(self) -> str:
3535
return self._text
3636

3737

3838
class BoldWrapper(TextTag):
3939
"""Wraps a tag in <b>"""
4040

41-
def __init__(self, wrapped):
41+
def __init__(self, wrapped: TextTag) -> None:
4242
self._wrapped = wrapped
4343

44-
def render(self):
44+
def render(self) -> str:
4545
return f"<b>{self._wrapped.render()}</b>"
4646

4747

4848
class ItalicWrapper(TextTag):
4949
"""Wraps a tag in <i>"""
5050

51-
def __init__(self, wrapped):
51+
def __init__(self, wrapped: TextTag) -> None:
5252
self._wrapped = wrapped
5353

54-
def render(self):
54+
def render(self) -> str:
5555
return f"<i>{self._wrapped.render()}</i>"
5656

5757

patterns/structural/facade.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,13 @@ class CPU:
3535
Simple CPU representation.
3636
"""
3737

38-
def freeze(self):
38+
def freeze(self) -> None:
3939
print("Freezing processor.")
4040

41-
def jump(self, position):
41+
def jump(self, position: str) -> None:
4242
print("Jumping to:", position)
4343

44-
def execute(self):
44+
def execute(self) -> None:
4545
print("Executing.")
4646

4747

@@ -50,7 +50,7 @@ class Memory:
5050
Simple memory representation.
5151
"""
5252

53-
def load(self, position, data):
53+
def load(self, position: str, data: str) -> None:
5454
print(f"Loading from {position} data: '{data}'.")
5555

5656

@@ -59,7 +59,7 @@ class SolidStateDrive:
5959
Simple solid state drive representation.
6060
"""
6161

62-
def read(self, lba, size):
62+
def read(self, lba: str, size: str) -> str:
6363
return f"Some data from sector {lba} with size {size}"
6464

6565

0 commit comments

Comments
 (0)