11
11
* Author(s): Yoch (https://github.com/yoch)
12
12
"""
13
13
14
+ try :
15
+ from typing import Dict , Any
16
+ except ImportError :
17
+ pass
18
+
19
+ from collections .abc import Callable , Iterator
20
+
14
21
15
22
class MQTTMatcher :
16
23
"""Intended to manage topic filters including wildcards.
@@ -27,22 +34,22 @@ class Node:
27
34
28
35
__slots__ = "children" , "content"
29
36
30
- def __init__ (self ):
31
- self .children = {}
37
+ def __init__ (self ) -> None :
38
+ self .children : Dict [ str , MQTTMatcher . Node ] = {}
32
39
self .content = None
33
40
34
- def __init__ (self ):
41
+ def __init__ (self ) -> None :
35
42
self ._root = self .Node ()
36
43
37
- def __setitem__ (self , key , value ) :
44
+ def __setitem__ (self , key : str , value : Callable [..., Any ]) -> None :
38
45
"""Add a topic filter :key to the prefix tree
39
46
and associate it to :value"""
40
47
node = self ._root
41
48
for sym in key .split ("/" ):
42
49
node = node .children .setdefault (sym , self .Node ())
43
50
node .content = value
44
51
45
- def __getitem__ (self , key ) :
52
+ def __getitem__ (self , key : str ) -> Callable [..., Any ] :
46
53
"""Retrieve the value associated with some topic filter :key"""
47
54
try :
48
55
node = self ._root
@@ -54,7 +61,7 @@ def __getitem__(self, key):
54
61
except KeyError :
55
62
raise KeyError (key ) from None
56
63
57
- def __delitem__ (self , key ) :
64
+ def __delitem__ (self , key : str ) -> None :
58
65
"""Delete the value associated with some topic filter :key"""
59
66
lst = []
60
67
try :
@@ -71,13 +78,13 @@ def __delitem__(self, key):
71
78
break
72
79
del parent .children [k ]
73
80
74
- def iter_match (self , topic ) :
81
+ def iter_match (self , topic : str ) -> Iterator [ Callable [..., Any ]] :
75
82
"""Return an iterator on all values associated with filters
76
83
that match the :topic"""
77
84
lst = topic .split ("/" )
78
85
normal = not topic .startswith ("$" )
79
86
80
- def rec (node , i = 0 ) :
87
+ def rec (node : MQTTMatcher . Node , i : int = 0 ) -> Iterator [ Callable [..., Any ]] :
81
88
if i == len (lst ):
82
89
if node .content is not None :
83
90
yield node .content
0 commit comments