Skip to content

Declaration of properties, attributes and command type with typing hints

Yury Matveyev requested to merge 53-server-declared-with-python-3-typing into develop

Closes #53 (closed) and #373 (closed)

This MR makes possible to declare type of properties, attributes and commands in high-API servers with type hint, if server executed with python >= 3.9. E.g.:

    host: str = device_property()

or

    @command
    def set_and_check_voltage(self, voltage_to_set: float) -> float:
        device.set_voltage(voltage_to_set)
        return device.get_voltage()

For the attributes type hint can be done at assignment (like property), or in the read/write method (like command).

    voltage: float = attribute()

    current = attribute()

    def read_current(self) -> float:
        return 10

At any cases the prority to obtain type is:

  1. dtype kword
  2. assignment
  3. read method
  4. write method

To define SPECTRUM and IMAGE attributes/properties/commands one can use list[type] or tuple[type]. In case of tuple the dimensions can be also specified from type hint: tuple[type, type], or tuple[tuple[type, type], tuple[type, type]]

Status of what done:

  • static attributes
  • dynamic attributes
  • static commands
  • dynamic commands
  • properties
  • documentation

Changes in the code:

  1. Properties:

dtype kword made optional with default value None and later. At the server creation if dtype is None we try to pick it from the Class.__annotations__

  1. Attributes: Added 2 additional filed to AttrData: has_dtype_kword, has_size_kword, which are False by default, and they set to True if users specify type and size in kwords (default behavior, as it was before). At the server creation if has_dtype_kword is False we try to pick it from the Class.__annotations__ and then from read/write_method.__annotations__.

In case of dynamic attribute, we try to get info during methods patching. Due to we cannot do Class.__annotations__, since attributes arr defined within the function and their assignment hints are not saved, so we can pick only from methods. I also had to modify slightly the logic of AttrData class in a way, that self.attr_args are now created at the last moment - since we post-updating dtype and format after init of AttrData

  1. We just look to the annotation of function. Again, with the priority to the standard kwords.

  2. There is additional parce_type_hint method in utils.py, that converts type hint to "tango format" of dtype

  3. tests of all possible combinations were added

  4. Tried to explain everything in docs.

Edited by Yury Matveyev

Merge request reports