18
18
Allow a request to pass down a chain of receivers until it is handled.
19
19
"""
20
20
21
- import abc
21
+ from abc import ABC , abstractmethod
22
+ from typing import Callable , Optional , Tuple , TypeVar
22
23
23
24
24
- class Handler ( metaclass = abc . ABCMeta ):
25
+ T = TypeVar ( "T" )
25
26
26
- def __init__ (self , successor = None ):
27
+
28
+ class Handler (ABC ):
29
+ def __init__ (self , successor : Optional [T ] = None ):
27
30
self .successor = successor
28
31
29
- def handle (self , request ) :
32
+ def handle (self , request : int ) -> None :
30
33
"""
31
34
Handle request and stop.
32
35
If can't - call next handler in chain.
@@ -38,8 +41,8 @@ def handle(self, request):
38
41
if not res and self .successor :
39
42
self .successor .handle (request )
40
43
41
- @abc . abstractmethod
42
- def check_range (self , request ) :
44
+ @abstractmethod
45
+ def check_range (self , request : int ) -> Optional [ bool ] :
43
46
"""Compare passed value to predefined interval"""
44
47
45
48
@@ -49,9 +52,9 @@ class ConcreteHandler0(Handler):
49
52
"""
50
53
51
54
@staticmethod
52
- def check_range (request ) :
55
+ def check_range (request : int ) -> Optional [ bool ] :
53
56
if 0 <= request < 10 :
54
- print ("request {} handled in handler 0" . format ( request ) )
57
+ print (f "request { request } handled in handler 0" )
55
58
return True
56
59
57
60
@@ -60,30 +63,30 @@ class ConcreteHandler1(Handler):
60
63
61
64
start , end = 10 , 20
62
65
63
- def check_range (self , request ) :
66
+ def check_range (self , request : int ) -> Optional [ bool ] :
64
67
if self .start <= request < self .end :
65
- print ("request {} handled in handler 1" . format ( request ) )
68
+ print (f "request { request } handled in handler 1" )
66
69
return True
67
70
68
71
69
72
class ConcreteHandler2 (Handler ):
70
73
"""... With helper methods."""
71
74
72
- def check_range (self , request ) :
75
+ def check_range (self , request : int ) -> Optional [ bool ] :
73
76
start , end = self .get_interval_from_db ()
74
77
if start <= request < end :
75
- print ("request {} handled in handler 2" . format ( request ) )
78
+ print (f "request { request } handled in handler 2" )
76
79
return True
77
80
78
81
@staticmethod
79
- def get_interval_from_db ():
82
+ def get_interval_from_db () -> Tuple [ int , int ] :
80
83
return (20 , 30 )
81
84
82
85
83
86
class FallbackHandler (Handler ):
84
87
@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 } " )
87
90
return False
88
91
89
92
0 commit comments