Skip to content

Commit 3514739

Browse files
authored
Merge pull request #342 from rednafi/master
Added type hinting to chain of responsibility pattern
2 parents 30a9eaf + 68e62a9 commit 3514739

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed

patterns/behavioral/chain_of_responsibility.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,18 @@
1818
Allow a request to pass down a chain of receivers until it is handled.
1919
"""
2020

21-
import abc
21+
from abc import ABC, abstractmethod
22+
from typing import Callable, Optional, Tuple, TypeVar
2223

2324

24-
class Handler(metaclass=abc.ABCMeta):
25+
T = TypeVar("T")
2526

26-
def __init__(self, successor=None):
27+
28+
class Handler(ABC):
29+
def __init__(self, successor: Optional[T] = None):
2730
self.successor = successor
2831

29-
def handle(self, request):
32+
def handle(self, request: int) -> None:
3033
"""
3134
Handle request and stop.
3235
If can't - call next handler in chain.
@@ -38,8 +41,8 @@ def handle(self, request):
3841
if not res and self.successor:
3942
self.successor.handle(request)
4043

41-
@abc.abstractmethod
42-
def check_range(self, request):
44+
@abstractmethod
45+
def check_range(self, request: int) -> Optional[bool]:
4346
"""Compare passed value to predefined interval"""
4447

4548

@@ -49,9 +52,9 @@ class ConcreteHandler0(Handler):
4952
"""
5053

5154
@staticmethod
52-
def check_range(request):
55+
def check_range(request: int) -> Optional[bool]:
5356
if 0 <= request < 10:
54-
print("request {} handled in handler 0".format(request))
57+
print(f"request {request} handled in handler 0")
5558
return True
5659

5760

@@ -60,30 +63,30 @@ class ConcreteHandler1(Handler):
6063

6164
start, end = 10, 20
6265

63-
def check_range(self, request):
66+
def check_range(self, request: int) -> Optional[bool]:
6467
if self.start <= request < self.end:
65-
print("request {} handled in handler 1".format(request))
68+
print(f"request {request} handled in handler 1")
6669
return True
6770

6871

6972
class ConcreteHandler2(Handler):
7073
"""... With helper methods."""
7174

72-
def check_range(self, request):
75+
def check_range(self, request: int) -> Optional[bool]:
7376
start, end = self.get_interval_from_db()
7477
if start <= request < end:
75-
print("request {} handled in handler 2".format(request))
78+
print(f"request {request} handled in handler 2")
7679
return True
7780

7881
@staticmethod
79-
def get_interval_from_db():
82+
def get_interval_from_db() -> Tuple[int, int]:
8083
return (20, 30)
8184

8285

8386
class FallbackHandler(Handler):
8487
@staticmethod
85-
def check_range(request):
86-
print("end of chain, no handler for {}".format(request))
88+
def check_range(request: int) -> Optional[bool]:
89+
print(f"end of chain, no handler for {request}")
8790
return False
8891

8992

0 commit comments

Comments
 (0)