from turtle import Turtle from typing import Any, Collection, Optional from controls.device import ActionDescriptor, SynchronyDevice, TraitDescriptor class TurtleDevice(SynchronyDevice): def open(self, name, **kwargs): self.turtle = Turtle(kwargs) super().open() def close(self): del self.turtle super().close() @property def trait_descriptors(self): traits = [attribute for attribute in vars(self.turtle).items() if (attribute[0].startswith('_') == False)] self.traits = [TraitDescriptor(*tr) for tr in traits] return self.traits @property def action_descriptors(self): actions = [(attribute, getattr(t, attribute)) for attribute in dir(t) if (attribute.startswith('_') == False)] self.actions = [TraitDescriptor(*ac) for ac in actions] return self.actions def read(self, trait_name): collection = self.traits return ([collection[i].info for i in range(len(collection)) if collection[i].name == trait_name]) def write(self, trait_name: str, value: Any) -> bool: collection = self.traits for i in range(len(collection)): if collection[i].name == trait_name: collection[i].info=value def execute(self, action_name: str, *args, **kwargs): self.turtle.action_name(args, *kwargs) def invalidate(self, trait_name: str): return super().invalidate(trait_name) def __getitem__(self, trait_name: str) -> Any | None: collection = self.traits return ([collection[i] for i in range(len(collection)) if collection[i].name == trait_name])