Skip to content

Commit baebfaa

Browse files
authored
Merge pull request #91 from DiamondLightSource/89-change-how-we-search-for-attributes
Change how we search for attributes
2 parents 35b1870 + f45ac5c commit baebfaa

File tree

2 files changed

+135
-8
lines changed

2 files changed

+135
-8
lines changed

src/fastcs/controller.py

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from collections.abc import Iterator
44
from copy import copy
55
from dataclasses import dataclass
6+
from typing import get_type_hints
67

78
from .attributes import Attribute
89
from .cs_methods import Command, Put, Scan
@@ -19,9 +20,14 @@ class SingleMapping:
1920

2021

2122
class BaseController:
23+
#: Attributes passed from the device at runtime.
24+
attributes: dict[str, Attribute]
25+
2226
def __init__(self, path: list[str] | None = None) -> None:
27+
if not hasattr(self, "attributes"):
28+
self.attributes = {}
2329
self._path: list[str] = path or []
24-
self.__sub_controller_tree: dict[str, BaseController] = {}
30+
self.__sub_controller_tree: dict[str, SubController] = {}
2531

2632
self._bind_attrs()
2733

@@ -37,11 +43,27 @@ def set_path(self, path: list[str]):
3743
self._path = path
3844

3945
def _bind_attrs(self) -> None:
40-
for attr_name in dir(self):
41-
attr = getattr(self, attr_name)
46+
# Using a dictionary instead of a set to maintain order.
47+
class_dir = {key: None for key in dir(type(self))}
48+
class_type_hints = get_type_hints(type(self))
49+
50+
for attr_name in {**class_dir, **class_type_hints}:
51+
if attr_name == "root_attribute":
52+
continue
53+
54+
attr = getattr(self, attr_name, None)
4255
if isinstance(attr, Attribute):
56+
if (
57+
attr_name in self.attributes
58+
and self.attributes[attr_name] is not attr
59+
):
60+
raise ValueError(
61+
f"`{type(self).__name__}` has conflicting attribute "
62+
f"`{attr_name}` already present in the attributes dict."
63+
)
4364
new_attribute = copy(attr)
4465
setattr(self, attr_name, new_attribute)
66+
self.attributes[attr_name] = new_attribute
4567

4668
def register_sub_controller(self, name: str, sub_controller: SubController):
4769
if name in self.__sub_controller_tree.keys():
@@ -52,7 +74,16 @@ def register_sub_controller(self, name: str, sub_controller: SubController):
5274
self.__sub_controller_tree[name] = sub_controller
5375
sub_controller.set_path(self.path + [name])
5476

55-
def get_sub_controllers(self) -> dict[str, BaseController]:
77+
if isinstance(sub_controller.root_attribute, Attribute):
78+
if name in self.attributes:
79+
raise TypeError(
80+
f"Cannot set SubController `{name}` root attribute "
81+
f"on the parent controller `{type(self).__name__}` "
82+
f"as it already has an attribute of that name."
83+
)
84+
self.attributes[name] = sub_controller.root_attribute
85+
86+
def get_sub_controllers(self) -> dict[str, SubController]:
5687
return self.__sub_controller_tree
5788

5889
def get_controller_mappings(self) -> list[SingleMapping]:
@@ -69,7 +100,6 @@ def _get_single_mapping(controller: BaseController) -> SingleMapping:
69100
scan_methods: dict[str, Scan] = {}
70101
put_methods: dict[str, Put] = {}
71102
command_methods: dict[str, Command] = {}
72-
attributes: dict[str, Attribute] = {}
73103
for attr_name in dir(controller):
74104
attr = getattr(controller, attr_name)
75105
match attr:
@@ -79,11 +109,15 @@ def _get_single_mapping(controller: BaseController) -> SingleMapping:
79109
scan_methods[attr_name] = scan_method
80110
case WrappedMethod(fastcs_method=Command(enabled=True) as command_method):
81111
command_methods[attr_name] = command_method
82-
case Attribute(enabled=True):
83-
attributes[attr_name] = attr
112+
113+
enabled_attributes = {
114+
name: attribute
115+
for name, attribute in controller.attributes.items()
116+
if attribute.enabled
117+
}
84118

85119
return SingleMapping(
86-
controller, scan_methods, put_methods, command_methods, attributes
120+
controller, scan_methods, put_methods, command_methods, enabled_attributes
87121
)
88122

89123

@@ -113,5 +147,7 @@ class SubController(BaseController):
113147
it as part of a larger device.
114148
"""
115149

150+
root_attribute: Attribute | None = None
151+
116152
def __init__(self) -> None:
117153
super().__init__()

tests/test_controller.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import pytest
22

3+
from fastcs.attributes import AttrR
34
from fastcs.controller import (
45
Controller,
56
SubController,
67
_get_single_mapping,
78
_walk_mappings,
89
)
10+
from fastcs.datatypes import Int
911

1012

1113
def test_controller_nesting():
@@ -33,3 +35,92 @@ def test_controller_nesting():
3335
ValueError, match=r"SubController is already registered under .*"
3436
):
3537
controller.register_sub_controller("c", sub_controller)
38+
39+
40+
class SomeSubController(SubController):
41+
def __init__(self):
42+
super().__init__()
43+
44+
sub_attribute = AttrR(Int())
45+
46+
root_attribute = AttrR(Int())
47+
48+
49+
class SomeController(Controller):
50+
annotated_attr: AttrR
51+
annotated_attr_not_defined_in_init: AttrR[int]
52+
equal_attr = AttrR(Int())
53+
annotated_and_equal_attr: AttrR[int] = AttrR(Int())
54+
55+
def __init__(self, sub_controller: SubController):
56+
self.attributes = {}
57+
58+
self.annotated_attr = AttrR(Int())
59+
self.attr_on_object = AttrR(Int())
60+
61+
self.attributes["_attributes_attr"] = AttrR(Int())
62+
self.attributes["_attributes_attr_equal"] = self.equal_attr
63+
64+
super().__init__()
65+
self.register_sub_controller("sub_controller", sub_controller)
66+
67+
68+
def test_attribute_parsing():
69+
sub_controller = SomeSubController()
70+
controller = SomeController(sub_controller)
71+
72+
mapping_walk = _walk_mappings(controller)
73+
74+
controller_mapping = next(mapping_walk)
75+
assert set(controller_mapping.attributes.keys()) == {
76+
"_attributes_attr",
77+
"annotated_attr",
78+
"_attributes_attr_equal",
79+
"annotated_and_equal_attr",
80+
"equal_attr",
81+
"sub_controller",
82+
}
83+
84+
assert SomeController.equal_attr is not controller.equal_attr
85+
assert (
86+
SomeController.annotated_and_equal_attr
87+
is not controller.annotated_and_equal_attr
88+
)
89+
90+
sub_controller_mapping = next(mapping_walk)
91+
assert sub_controller_mapping.attributes == {
92+
"sub_attribute": sub_controller.sub_attribute,
93+
}
94+
95+
96+
def test_attribute_in_both_class_and_get_attributes():
97+
class FailingController(Controller):
98+
duplicate_attribute = AttrR(Int())
99+
100+
def __init__(self):
101+
self.attributes = {"duplicate_attribute": AttrR(Int())}
102+
super().__init__()
103+
104+
with pytest.raises(
105+
ValueError,
106+
match=(
107+
"`FailingController` has conflicting attribute `duplicate_attribute` "
108+
"already present in the attributes dict."
109+
),
110+
):
111+
FailingController()
112+
113+
114+
def test_root_attribute():
115+
class FailingController(SomeController):
116+
sub_controller = AttrR(Int())
117+
118+
with pytest.raises(
119+
TypeError,
120+
match=(
121+
"Cannot set SubController `sub_controller` root attribute "
122+
"on the parent controller `FailingController` as it already "
123+
"has an attribute of that name."
124+
),
125+
):
126+
next(_walk_mappings(FailingController(SomeSubController())))

0 commit comments

Comments
 (0)