Skip to content

add type hints to matcher.py #137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions adafruit_minimqtt/matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
* Author(s): Yoch (https://github.com/yoch)
"""

try:
from typing import Dict
except ImportError:
pass


class MQTTMatcher:
"""Intended to manage topic filters including wildcards.
Expand All @@ -27,22 +32,22 @@ class Node:

__slots__ = "children", "content"

def __init__(self):
self.children = {}
def __init__(self) -> None:
self.children: Dict[str, MQTTMatcher.Node] = {}
self.content = None

def __init__(self):
def __init__(self) -> None:
self._root = self.Node()

def __setitem__(self, key, value):
def __setitem__(self, key: str, value) -> None:
"""Add a topic filter :key to the prefix tree
and associate it to :value"""
node = self._root
for sym in key.split("/"):
node = node.children.setdefault(sym, self.Node())
node.content = value

def __getitem__(self, key):
def __getitem__(self, key: str):
"""Retrieve the value associated with some topic filter :key"""
try:
node = self._root
Expand All @@ -54,7 +59,7 @@ def __getitem__(self, key):
except KeyError:
raise KeyError(key) from None

def __delitem__(self, key):
def __delitem__(self, key: str) -> None:
"""Delete the value associated with some topic filter :key"""
lst = []
try:
Expand All @@ -71,13 +76,13 @@ def __delitem__(self, key):
break
del parent.children[k]

def iter_match(self, topic):
def iter_match(self, topic: str):
"""Return an iterator on all values associated with filters
that match the :topic"""
lst = topic.split("/")
normal = not topic.startswith("$")

def rec(node, i=0):
def rec(node: MQTTMatcher.Node, i: int = 0):
if i == len(lst):
if node.content is not None:
yield node.content
Expand Down