-
Notifications
You must be signed in to change notification settings - Fork 6
Validate hinted methods #320
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
base: main
Are you sure you want to change the base?
Changes from all commits
a1ad5cd
5ce671d
b2c003d
ab37703
b69ac86
df6b7d4
c229e33
4f31e48
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -3,14 +3,21 @@ | |||||
| from collections import Counter | ||||||
| from collections.abc import Sequence | ||||||
| from copy import deepcopy | ||||||
| from typing import _GenericAlias, get_args, get_origin, get_type_hints # type: ignore | ||||||
| from typing import ( # type: ignore | ||||||
| TypeVar, | ||||||
| _GenericAlias, # type: ignore | ||||||
| get_args, | ||||||
| get_origin, | ||||||
| get_type_hints, | ||||||
| ) | ||||||
|
|
||||||
| from fastcs.attributes import AnyAttributeIO, Attribute, AttrR, AttrW, HintedAttribute | ||||||
| from fastcs.logging import bind_logger | ||||||
| from fastcs.methods import Command, Scan, UnboundCommand, UnboundScan | ||||||
| from fastcs.methods import Command, Method, Scan, UnboundCommand, UnboundScan | ||||||
| from fastcs.tracer import Tracer | ||||||
|
|
||||||
| logger = bind_logger(logger_name=__name__) | ||||||
| T = TypeVar("T") | ||||||
|
|
||||||
|
|
||||||
| class BaseController(Tracer): | ||||||
|
|
@@ -51,6 +58,7 @@ def __init__( | |||||
| self.__scan_methods: dict[str, Scan] = {} | ||||||
|
|
||||||
| self.__hinted_attributes: dict[str, HintedAttribute] = {} | ||||||
| self.__hinted_methods: dict[str, type[Method]] = {} | ||||||
| self.__hinted_sub_controllers: dict[str, type[BaseController]] = {} | ||||||
| self._find_type_hints() | ||||||
|
|
||||||
|
|
@@ -87,6 +95,9 @@ def _find_type_hints(self): | |||||
| elif isinstance(hint, type) and issubclass(hint, BaseController): | ||||||
| self.__hinted_sub_controllers[name] = hint | ||||||
|
|
||||||
| elif isinstance(hint, type) and issubclass(hint, Method): | ||||||
| self.__hinted_methods[name] = hint | ||||||
|
|
||||||
| def _bind_attrs(self) -> None: | ||||||
| """Search for Attributes and Methods to bind them to this instance. | ||||||
|
|
||||||
|
|
@@ -168,47 +179,70 @@ def post_initialise(self): | |||||
| self._connect_attribute_ios() | ||||||
|
|
||||||
| def _validate_type_hints(self): | ||||||
| """Validate all `Attribute` and `Controller` type-hints were introspected""" | ||||||
| """Validate all type-hints were introspected""" | ||||||
| for name in self.__hinted_attributes: | ||||||
| self._validate_hinted_attribute(name) | ||||||
|
|
||||||
| for name in self.__hinted_sub_controllers: | ||||||
| self._validate_hinted_controller(name) | ||||||
|
|
||||||
| for name in self.__hinted_methods: | ||||||
| self._validate_hinted_method(name) | ||||||
|
|
||||||
| for subcontroller in self.sub_controllers.values(): | ||||||
| subcontroller._validate_type_hints() # noqa: SLF001 | ||||||
|
|
||||||
| def _validate_hinted_member(self, name: str, expected_type: type[T]) -> T: | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not just
Suggested change
What is the difference?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here, I'm passing in a class to |
||||||
| """Validate that a hinted member exists on the controller""" | ||||||
| member = getattr(self, name, None) | ||||||
| if member is None or not isinstance(member, expected_type): | ||||||
| raise RuntimeError() | ||||||
| return member | ||||||
|
|
||||||
| def _validate_hinted_method(self, name: str): | ||||||
| """Check that a `Method` with the given name exists on the controller""" | ||||||
| try: | ||||||
| method = self._validate_hinted_member(name, Method) | ||||||
| except RuntimeError: | ||||||
| raise RuntimeError( | ||||||
| f"Controller `{self.__class__.__name__}` failed to introspect " | ||||||
| f"hinted method `{name}` during initialisation" | ||||||
| ) from None | ||||||
|
|
||||||
| logger.debug( | ||||||
| "Validated hinted method", name=name, controller=self, method=method | ||||||
| ) | ||||||
shihab-dls marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
|
||||||
| def _validate_hinted_attribute(self, name: str): | ||||||
| """Check that an `Attribute` with the given name exists on the controller""" | ||||||
| attr = getattr(self, name, None) | ||||||
| if attr is None or not isinstance(attr, Attribute): | ||||||
| try: | ||||||
| attr = self._validate_hinted_member(name, Attribute) | ||||||
| except RuntimeError: | ||||||
| raise RuntimeError( | ||||||
| f"Controller `{self.__class__.__name__}` failed to introspect " | ||||||
| f"hinted attribute `{name}` during initialisation" | ||||||
| ) | ||||||
| else: | ||||||
| logger.debug( | ||||||
| "Validated hinted attribute", | ||||||
| name=name, | ||||||
| controller=self, | ||||||
| attribute=attr, | ||||||
| ) | ||||||
| ) from None | ||||||
|
|
||||||
| logger.debug( | ||||||
| "Validated hinted attribute", name=name, controller=self, attribute=attr | ||||||
| ) | ||||||
shihab-dls marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
|
||||||
| def _validate_hinted_controller(self, name: str): | ||||||
| """Check that a sub controller with the given name exists on the controller""" | ||||||
| controller = getattr(self, name, None) | ||||||
| if controller is None or not isinstance(controller, BaseController): | ||||||
| try: | ||||||
| controller = self._validate_hinted_member(name, BaseController) | ||||||
| except RuntimeError: | ||||||
| raise RuntimeError( | ||||||
| f"Controller `{self.__class__.__name__}` failed to introspect " | ||||||
| f"hinted controller `{name}` during initialisation" | ||||||
| ) | ||||||
| else: | ||||||
| logger.debug( | ||||||
| "Validated hinted sub controller", | ||||||
| name=name, | ||||||
| controller=self, | ||||||
| sub_controller=controller, | ||||||
| ) | ||||||
| ) from None | ||||||
|
|
||||||
| logger.debug( | ||||||
| "Validated hinted sub controller", | ||||||
| name=name, | ||||||
| controller=self, | ||||||
| sub_controller=controller, | ||||||
| ) | ||||||
|
|
||||||
| def _connect_attribute_ios(self) -> None: | ||||||
| """Connect ``Attribute`` callbacks to ``AttributeIO``s""" | ||||||
|
|
@@ -245,14 +279,27 @@ def set_path(self, path: list[str]): | |||||
| for attribute in self.__attributes.values(): | ||||||
| attribute.set_path(path) | ||||||
|
|
||||||
| def _check_for_name_clash(self, name: str): | ||||||
| namespaces = { | ||||||
| "attribute": self.__attributes, | ||||||
| "sub controller": self.__sub_controllers, | ||||||
| "scan method": self.__scan_methods, | ||||||
| "command method": self.__command_methods, | ||||||
| } | ||||||
|
|
||||||
| for kind, namespace in namespaces.items(): | ||||||
| if name in namespace: | ||||||
| raise ValueError( | ||||||
| f"Controller {self} has existing {kind} {name}: {namespace[name]}" | ||||||
| ) | ||||||
|
|
||||||
| def add_attribute(self, name, attr: Attribute): | ||||||
| if name in self.__attributes: | ||||||
| raise ValueError( | ||||||
| f"Cannot add attribute {attr}. " | ||||||
| f"Controller {self} has has existing attribute {name}: " | ||||||
| f"{self.__attributes[name]}" | ||||||
| ) | ||||||
| elif name in self.__hinted_attributes: | ||||||
| try: | ||||||
| self._check_for_name_clash(name) | ||||||
| except ValueError as exc: | ||||||
| raise ValueError(f"Cannot add attribute {attr}.") from exc | ||||||
|
|
||||||
| if name in self.__hinted_attributes: | ||||||
| hint = self.__hinted_attributes[name] | ||||||
| if not isinstance(attr, hint.attr_type): | ||||||
| raise RuntimeError( | ||||||
|
|
@@ -267,12 +314,6 @@ def add_attribute(self, name, attr: Attribute): | |||||
| f"Expected '{hint.dtype.__name__}', " | ||||||
| f"got '{attr.datatype.dtype.__name__}'." | ||||||
| ) | ||||||
| elif name in self.__sub_controllers.keys(): | ||||||
| raise ValueError( | ||||||
| f"Cannot add attribute {attr}. " | ||||||
| f"Controller {self} has existing sub controller {name}: " | ||||||
| f"{self.__sub_controllers[name]}" | ||||||
| ) | ||||||
|
|
||||||
| attr.set_name(name) | ||||||
| attr.set_path(self.path) | ||||||
|
|
@@ -284,13 +325,12 @@ def attributes(self) -> dict[str, Attribute]: | |||||
| return self.__attributes | ||||||
|
|
||||||
| def add_sub_controller(self, name: str, sub_controller: BaseController): | ||||||
| if name in self.__sub_controllers.keys(): | ||||||
| raise ValueError( | ||||||
| f"Cannot add sub controller {sub_controller}. " | ||||||
| f"Controller {self} has existing sub controller {name}: " | ||||||
| f"{self.__sub_controllers[name]}" | ||||||
| ) | ||||||
| elif name in self.__hinted_sub_controllers: | ||||||
| try: | ||||||
| self._check_for_name_clash(name) | ||||||
| except ValueError as exc: | ||||||
| raise ValueError(f"Cannot add sub controller {sub_controller}.") from exc | ||||||
|
|
||||||
| if name in self.__hinted_sub_controllers: | ||||||
| hint = self.__hinted_sub_controllers[name] | ||||||
| if not isinstance(sub_controller, hint): | ||||||
| raise RuntimeError( | ||||||
|
|
@@ -299,12 +339,6 @@ def add_sub_controller(self, name: str, sub_controller: BaseController): | |||||
| f"Expected '{hint.__name__}' got " | ||||||
| f"'{sub_controller.__class__.__name__}'." | ||||||
| ) | ||||||
| elif name in self.__attributes: | ||||||
| raise ValueError( | ||||||
| f"Cannot add sub controller {sub_controller}. " | ||||||
| f"Controller {self} has existing attribute {name}: " | ||||||
| f"{self.__attributes[name]}" | ||||||
| ) | ||||||
|
|
||||||
| sub_controller.set_path(self.path + [name]) | ||||||
| self.__sub_controllers[name] = sub_controller | ||||||
|
|
@@ -317,7 +351,24 @@ def add_sub_controller(self, name: str, sub_controller: BaseController): | |||||
| def sub_controllers(self) -> dict[str, BaseController]: | ||||||
| return self.__sub_controllers | ||||||
|
|
||||||
| def _validated_method(self, name: str, method: Method): | ||||||
| if name in self.__hinted_methods: | ||||||
| hint = self.__hinted_methods[name] | ||||||
| if not isinstance(method, hint): | ||||||
| raise RuntimeError( | ||||||
| f"Controller '{self.__class__.__name__}' introspection of " | ||||||
| f"hinted method '{name}' does not match defined type. " | ||||||
| f"Expected '{hint.__name__}' got " | ||||||
| f"'{method.__class__.__name__}'." | ||||||
| ) | ||||||
|
|
||||||
| def add_command(self, name: str, command: Command): | ||||||
| try: | ||||||
| self._check_for_name_clash(name) | ||||||
| self._validated_method(name, command) | ||||||
| except (ValueError, RuntimeError) as exc: | ||||||
| raise exc.__class__(f"Cannot add command method {command}.") from exc | ||||||
|
|
||||||
| self.__command_methods[name] = command | ||||||
| super().__setattr__(name, command) | ||||||
|
|
||||||
|
|
@@ -326,6 +377,12 @@ def command_methods(self) -> dict[str, Command]: | |||||
| return self.__command_methods | ||||||
|
|
||||||
| def add_scan(self, name: str, scan: Scan): | ||||||
| try: | ||||||
| self._check_for_name_clash(name) | ||||||
| self._validated_method(name, scan) | ||||||
| except (ValueError, RuntimeError) as exc: | ||||||
| raise exc.__class__(f"Cannot add scan method {scan}.") from exc | ||||||
|
|
||||||
| self.__scan_methods[name] = scan | ||||||
| super().__setattr__(name, scan) | ||||||
|
|
||||||
|
|
||||||
Uh oh!
There was an error while loading. Please reload this page.