Declare attributes with type hints and fill them from a shared backend

Aperta
#469 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 6 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
35/100
Tipo di issue
Funzionalità
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
api, backend

Direzione di ricerca

Start by reading the migration context in issues #402, #388, and #426, then inspect the existing attribute and controller APIs related to #466. Trace how controller type hints are collected, attributes are added, and initialization is validated. Done means the acceptance criteria are implemented, with SCPI and Eiger demos covering declared and introspected attributes.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

As part of migrating changes from #402 (see #388, decision 3, and #426), attributes should be declarable as type hints in the controller class body. Their getters, setters and metadata can then supplied later, either from static metadata written by the driver author or from what the device reports about itself.

Even with getters/setters (#466), a driver that talks to many parameters over one protocol has to create every attribute by hand in init. It also has to write a getter/setter pair for each one that differs only in which parameter it addresses:

class TemperatureController(Controller):
    def __init__(self, connection):
        self._conn = connection
        super().__init__()
        self.ramp_rate = AttrRW(
            float,
            getter=Polled(self._getter("R"), period=0.2),
            setter=self._setter("R"),
            precision=3
            units="K/s",
        )                                                                        
        self.power = AttrR(
            float, getter=Polled(self._getter("P"), period=0.2), precision=3, units="W"
        )

    def _getter(self, token): ...
    def _setter(self, token): ...

Moreover, a type hint on a controller (attr: AttrR[int]) does not create an attribute. It only records what introspection must add. When initialise() constructs an attribute and adds it under that name, add_attribute validates it against the hint, and after initialise() every hinted name is checked to exist. Until then, self.attr does not exist, even though a type checker treats it as an AttrR[int]. This means that code in __init__ cannot reference a hinted attribute, so anything that needs it, such as a sub controller wiring, a callback or a scan, has to wait until after the initialise() that creates it. Creating hinted attributes during init and filling them during initialise() would remove that ordering constraint, and would let initialise() run in parallel across controllers, allowing them to cross-reference each others attributes.

With an API that allows for these kinds of type hints, a single backend object can provide get/set for all of them, and the hint's Annotated extras can say which parameter each attribute uses, plus its metadata and polling:

class SCPIBackend:
    async def get(self, param: SCPIParam) -> str: ...
    async def set(self, value: DType, param: SCPIParam) -> None: ...


class TemperatureController(Controller):
    ramp_rate: Annotated[
        AttrRW[float], SCPIParam("R"), FloatMeta(precision=3, units="K/s")
    ]
    power: Annotated[AttrR[float], SCPIParam("P"), FloatMeta(precision=3, units="W")]

    async def initialise(self) -> None:
        self.filler.fill_from_annotated(
            SCPIBackend(self.connection), schedule=Polled(period=0.2)
        )

Here, the backend is passed into a method on filler. filler should be an object created on the controller at construction time. This object is responsible for collecting type-hints and binding attributes (at _init_), to be filled later in initialise(). fill_from_backend is a method which assumes all information about an attribute are annotated in the class definition (i.e., the datatype, required getter / setter args, and optional metadata are all provided).

For an introspectable device, a hint can be a promise that is kept at runtime, as an author may not know the datatype, required getter / setter args, and metadata an attribute should hold until after a connection is established:

class EigerDetector(Controller):
    state: AttrR  # datatype only known from the device
    count_time: AttrRW[float] # param not knowne

    async def initialise(self) -> None:
        for subsystem, param, data in await self._parameter_tree():
            self.filler
                param,
attr_type=AttrRW[_datat
            )
        self.filler.check_filled()

Acceptance Criteria

  • A hint that names its datatype (e.g., AttrRW[float]) creates an unfilled attribute by the time init returns, so the rest of init can reference it.
  • A hint that names no datatype (e.g., AttrR) is a promise. check_filled() raises if it has not been added by the end of initialisation.
  • An AttrBackend protocol (get(*args) / set(value, *args)) lets one object serve the IO for many attributes, with args identifying which one.
  • Annotated hint extras are separated into backend arguments, *Meta metadata and a Polled/NotPolled schedule. Extras the backend cannot take are rejected.
  • Declared attributes can be filled from a backend in one call. A single named attribute can also be filled (or added if it was not declared) with an explicit type, args, schedule and metadata.
  • Filling checks access mode, datatype and metadata against the hint, and raises if they disagree.
  • Attributes not built from a backend can still be filled with plain getters/setters.
  • Demos cover a static, hand-declared device (SCPI) and an introspectable device (Eiger).
Lingua principale
Python
Stelle
6
Fork
8
Merge medio
3g 22h
PR unite (30g)
3

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di DiamondLightSource/fastcs

Tutte le issue di DiamondLightSource/fastcs

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.