-
Notifications
You must be signed in to change notification settings - Fork 352
Expand file tree
/
Copy pathfunction.py
More file actions
215 lines (170 loc) · 6.66 KB
/
function.py
File metadata and controls
215 lines (170 loc) · 6.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
from __future__ import annotations
from functools import cached_property
from typing import TYPE_CHECKING, Any
from qcodes.metadatable import MetadatableWithName
from qcodes.validators import Validator, validate_all
from .command import Command
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from qcodes.instrument import InstrumentBase
class Function(MetadatableWithName):
"""
Defines a function that an instrument can execute.
This class is meant for simple cases, principally things that
map to simple commands like ``*RST`` (reset) or those with just a few
arguments.
It requires a fixed argument count, and positional args
only.
You execute this function object like a normal function, or use its
.call method.
Note:
Parsers only apply if call_cmd is a string. The function form of
call_cmd should do its own parsing.
Note:
We do not recommend the usage of Function for any new driver.
Function does not add any significant features over a method
defined on the class.
Args:
name: the local name of this function
instrument: an instrument that handles this
function. Default None.
call_cmd: command to execute on
the instrument:
- a string (with positional fields to .format, "{}" or "{0}" etc)
you can only use a string if an instrument is provided,
this string will be passed to instrument.write
- a function (with arg count matching args list)
args: list of Validator objects, one for
each arg to the Function
arg_parser: function to transform the input arg(s)
to encoded value(s) sent to the instrument. If there are multiple
arguments, this function should accept all the arguments in order,
and return a tuple of values.
return_parser: function to transform the response
from the instrument to the final output value. may be a
type casting function like `int` or `float`. If None (default),
will not wait for or read any response.
docstring: documentation string for the __doc__
field of the object. The __doc__ field of the instance is used by
some help systems, but not all (particularly not builtin `help()`)
**kwargs: Arbitrary keyword arguments passed to parent class
"""
def __init__(
self,
name: str,
instrument: InstrumentBase | None = None,
call_cmd: str | Callable[..., Any] | None = None,
args: Sequence[Validator[Any]] | None = None,
arg_parser: Callable[..., Any] | None = None,
return_parser: Callable[..., Any] | None = None,
docstring: str | None = None,
**kwargs: Any,
):
super().__init__(**kwargs)
self._instrument = instrument
self.name = name
if docstring is not None:
self.__doc__ = docstring
if args is None:
args = []
self._set_args(args)
self._set_call(call_cmd, arg_parser, return_parser)
def _set_args(self, args: Sequence[Validator[Any]]) -> None:
for arg in args:
if not isinstance(arg, Validator):
raise TypeError("all args must be Validator objects")
self._args = args
self._arg_count = len(args)
def _set_call(
self,
call_cmd: str | Callable[..., Any] | None,
arg_parser: Callable[..., Any] | None,
return_parser: Callable[..., Any] | None,
) -> None:
if self._instrument:
ask_or_write = self._instrument.write
if isinstance(call_cmd, str) and return_parser:
ask_or_write = self._instrument.ask
else:
ask_or_write = None
self._call = Command(
arg_count=self._arg_count,
cmd=call_cmd,
exec_str=ask_or_write,
input_parser=arg_parser,
output_parser=return_parser,
)
def validate(self, *args: Any) -> None:
"""
Check that all arguments to this Function are allowed.
Args:
*args: Variable length argument list, passed to the call_cmd
"""
if self._instrument:
func_name = (
(
getattr(self._instrument, "name", "")
or str(self._instrument.__class__)
)
+ "."
+ self.name
)
else:
func_name = self.name
if len(args) != self._arg_count:
raise TypeError(
f"{func_name} called with {len(args)} args but requires {self._arg_count}"
)
validate_all(*zip(self._args, args), context="Function: " + func_name)
def __call__(self, *args: Any) -> Any:
self.validate(*args)
return self._call(*args)
def call(self, *args: Any) -> Any:
"""
Call methods wraps __call__
Args:
*args: argument to pass to Command __call__ function
"""
return self.__call__(*args)
def get_attrs(self) -> list[str]:
"""
Attributes recreated as properties in the RemoteFunction proxy.
Returns (list): __doc__, _args, and _arg_count get proxied
"""
return ["__doc__", "_args", "_arg_count"]
@property
def short_name(self) -> str:
"""
Name excluding name of any instrument that this function may be
bound to.
"""
return self.name
@cached_property
def full_name(self) -> str:
"""
Name of the function including the name of the instrument and
submodule that the function may be bound to. The names are separated
by underscores, like this: ``instrument_submodule_function``.
"""
return "_".join(self.name_parts)
@property
def name_parts(self) -> list[str]:
"""
List of the parts that make up the full name of this function
"""
if self.instrument is not None:
name_parts = getattr(self.instrument, "name_parts", [])
if name_parts == []:
# add fallback for the case where someone has bound
# the function to something that is not an instrument
# but perhaps it has a name anyway?
name = getattr(self.instrument, "name", None)
if name is not None:
name_parts = [name]
else:
name_parts = []
name_parts.append(self.short_name)
return name_parts
@property
def instrument(self) -> InstrumentBase | None:
return self._instrument