From 10b9cf7ced0cb2a1d054397c35e4b4bb5d1de19f Mon Sep 17 00:00:00 2001 From: Tianhao Fu Date: Sun, 8 Sep 2024 17:25:35 -0400 Subject: [PATCH] Disallow Changing Devices' Tags after Registration (#391) * Added `lock_tag()`. (#390) * Comments updated. (#390) * Using `lock_tag()`. (#390) * Comments updated. (#390) --- leads/dt/controller.py | 1 + leads/dt/device.py | 11 ++++++++++- leads/dt/registry.py | 1 + 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/leads/dt/controller.py b/leads/dt/controller.py index 8d40e032..718c8903 100644 --- a/leads/dt/controller.py +++ b/leads/dt/controller.py @@ -15,6 +15,7 @@ def __init__(self) -> None: def _attach_device(self, tag: str, device: Device) -> None: self._devices[tag] = device device.tag(tag) + device.lock_tag() def devices(self) -> list[Device]: """ diff --git a/leads/dt/device.py b/leads/dt/device.py index 89dc8263..c9dac551 100644 --- a/leads/dt/device.py +++ b/leads/dt/device.py @@ -12,6 +12,7 @@ def __init__(self, *args, **kwargs) -> None: # real signature unknown def __init__(self, *pins: int | str) -> None: self._tag: str = "" + self._tag_locked: bool = False self._parent_tags: tuple[str, ...] = () self._pins: tuple[int | str, ...] = pins @@ -29,12 +30,20 @@ def level(self) -> int: def tag(self, tag: str | None = None) -> str | None: """ Set or get the tag of the device. + The tag will not be set if it is locked. :param tag: the tag or None if getter mode :return: the tag or None if setter mode """ if tag is None: return self._tag - self._tag = tag + if not self._tag_locked: + self._tag = tag + + def lock_tag(self) -> None: + """ + Lock the tag of the device. + """ + self._tag_locked = True def parent_tags(self) -> tuple[str, ...]: """ diff --git a/leads/dt/registry.py b/leads/dt/registry.py index 9603e097..457bca7f 100644 --- a/leads/dt/registry.py +++ b/leads/dt/registry.py @@ -57,6 +57,7 @@ def register_controller(tag: str, c: Controller, parent: str | None = None) -> N _controllers[parent].device(tag, c) else: c.tag(tag) + c.lock_tag() _controllers[tag] = c