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

オープン
#469 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 6 日以内に返信

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
35/100
issue の種類
機能追加
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
python
領域
api, backend

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

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).
主要言語
Python
スター
6
フォーク
8
平均マージ
3日 22時間
マージ済み PR(30日)
3

環境構築

Codespaces で開く

このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

DiamondLightSource/fastcs のほかの issue

DiamondLightSource/fastcs の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。