qcodes.utils

Classes:

DelayedKeyboardInterrupt([context])

A context manager to wrap a piece of code to ensure that a KeyboardInterrupt is not triggered by a SIGINT during the execution of this context.

DelegateAttributes()

Mixin class to create attributes of this object by delegating them to one or more dictionaries and/or objects.

NumpyJSONEncoder(*[, skipkeys, ...])

This JSON encoder adds support for serializing types that the built-in json module does not support out-of-the-box.

ParameterDiff(left_only, right_only, changed)

Create new instance of ParameterDiff(left_only, right_only, changed)

RespondingThread(target[, args, kwargs])

Thread subclass for parallelizing execution.

Exceptions:

QCoDeSDeprecationWarning

A DeprecationWarning used internally in QCoDeS.

Functions:

attribute_set_to(object_, attribute_name, ...)

This context manager allows to change a given attribute of a given object to a new value, and the original value is reverted upon exit of the context manager.

checked_getattr(instance, attribute, ...)

Like getattr but raises type error if not of expected type.

checked_getattr_indexed(instance, attribute, ...)

Like getattr_indexed but raises type error if not of expected type.

convert_legacy_version_to_supported_version(ver)

Convert a legacy version str containing single chars rather than numbers to a regular version string.

deep_update(dest, update)

Recursively update one JSON structure with another.

deprecate([reason, alternative])

A utility function to decorate deprecated functions and classes.

diff_param_values(left_snapshot, right_snapshot)

Given two snapshots, returns the differences between parameter values in each.

extract_param_values(snapshot)

Given a snapshot, returns a dictionary from instrument and parameter names onto parameter values.

full_class(obj)

The full importable path to an object's class.

get_all_installed_package_versions()

Return a dictionary of the currently installed packages and their versions.

get_qcodes_path(*subfolder)

Return full file path of the QCoDeS module.

get_qcodes_user_path(*file_parts)

Get ~/.qcodes path or if defined the path defined in the QCODES_USER_PATH environment variable.

getattr_indexed(instance, attribute)

Similar to getattr but allows indexing the returned attribute.

is_function(f, arg_count[, coroutine])

Check and require a function that can accept the specified number of positional arguments, which either is or is not a coroutine type casting "functions" are allowed, but only in the 1-argument form.

is_qcodes_installed_editably()

Try to ask pip whether QCoDeS is installed in editable mode and return the answer a boolean.

issue_deprecation_warning(what[, reason, ...])

Issue a QCoDeSDeprecationWarning with a consistently formatted message

list_of_data_to_maybe_ragged_nd_array(...[, ...])

Convert a (nested) Sequence of data to numpy arrays.

partial_with_docstring(func, docstring, **kwargs)

We want to have a partial function which will allow us to access the docstring through the python built-in help function.

qcodes_abstractmethod(funcobj)

A decorator indicating abstract methods.

strip_attrs(obj[, whitelist])

Irreversibly remove all direct instance attributes of object, to help with disposal, breaking circular references.

thread_map(callables[, args, kwargs])

Evaluate a sequence of callables in separate threads, returning a list of their return values.

class qcodes.utils.DelayedKeyboardInterrupt(context: Mapping[str, AttributeValue] | None = None)[source]

Bases: object

A context manager to wrap a piece of code to ensure that a KeyboardInterrupt is not triggered by a SIGINT during the execution of this context. A second SIGINT will trigger the KeyboardInterrupt immediately.

Inspired by https://stackoverflow.com/questions/842557/how-to-prevent-a-block-of-code-from-being-interrupted-by-keyboardinterrupt-in-py

Parameters:

context – A dictionary of attributes to be logged when the KeyboardInterrupt is triggered. This is useful for debugging where the interrupt was triggered. The attributes should be compatible with OpenTelemetry’s Attributes type.

Attributes:

Methods:

handler(sig, frame)

forceful_handler(frame)

signal_received: tuple[int, FrameType | None] | None = None
old_handler: Callable[[int, FrameType | None], Any] | int | None = None
handler(sig: int, frame: FrameType | None) None[source]
forceful_handler(frame: FrameType | None) None[source]
class qcodes.utils.DelegateAttributes[source]

Bases: object

Mixin class to create attributes of this object by delegating them to one or more dictionaries and/or objects.

Also fixes __dir__ so the delegated attributes will show up in dir() and autocomplete.

Attribute resolution order:
  1. Real attributes of this object.

  2. Keys of each dictionary in delegate_attr_dicts (in order).

  3. Attributes of each object in delegate_attr_objects (in order).

Attributes:

delegate_attr_dicts

A list of names (strings) of dictionaries which are (or will be) attributes of self, whose keys should be treated as attributes of self.

delegate_attr_objects

A list of names (strings) of objects which are (or will be) attributes of self, whose attributes should be passed through to self.

omit_delegate_attrs

A list of attribute names (strings) to not delegate to any other dictionary or object.

delegate_attr_dicts: ClassVar[list[str]] = []

A list of names (strings) of dictionaries which are (or will be) attributes of self, whose keys should be treated as attributes of self.

delegate_attr_objects: ClassVar[list[str]] = []

A list of names (strings) of objects which are (or will be) attributes of self, whose attributes should be passed through to self.

omit_delegate_attrs: ClassVar[list[str]] = []

A list of attribute names (strings) to not delegate to any other dictionary or object.

class qcodes.utils.NumpyJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

This JSON encoder adds support for serializing types that the built-in json module does not support out-of-the-box. See the docstring of the default method for the description of all conversions.

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an RecursionError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

Methods:

default(o)

List of conversions that this encoder performs:

default(o: Any) Any[source]

List of conversions that this encoder performs:

  • numpy.generic (all integer, floating, and other types) gets converted to its python equivalent using its item method (see numpy docs for more information, https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html).

  • numpy.ndarray gets converted to python list using its tolist method.

  • Complex number (a number that conforms to numbers.Complex ABC) gets converted to a dictionary with fields re and im containing floating numbers for the real and imaginary parts respectively, and a field __dtype__ containing value complex.

  • Numbers with uncertainties (numbers that conforms to uncertainties.UFloat) get converted to a dictionary with fields nominal_value and std_dev containing floating numbers for the nominal and uncertainty parts respectively, and a field __dtype__ containing value UFloat.

  • Object with a _JSONEncoder method get converted the return value of that method.

  • Objects which support the pickle protocol get converted using the data provided by that protocol.

  • Other objects which cannot be serialized get converted to their string representation (using the str function).

class qcodes.utils.ParameterDiff(left_only, right_only, changed)[source]

Bases: NamedTuple

Create new instance of ParameterDiff(left_only, right_only, changed)

Attributes:

left_only

Alias for field number 0

right_only

Alias for field number 1

changed

Alias for field number 2

left_only: dict[str | tuple[str, str], Any]

Alias for field number 0

right_only: dict[str | tuple[str, str], Any]

Alias for field number 1

changed: dict[str | tuple[str, str], tuple[Any, Any]]

Alias for field number 2

exception qcodes.utils.QCoDeSDeprecationWarning[source]

Bases: RuntimeWarning

A DeprecationWarning used internally in QCoDeS. This fixes DeprecationWarning being suppressed by default.

class qcodes.utils.RespondingThread(target: Callable[..., T], args: Sequence[Any] = (), kwargs: dict[str, Any] | None = None, *args2: Any, **kwargs2: Any)[source]

Bases: Thread, Generic[T]

Thread subclass for parallelizing execution. Behaves like a regular thread but returns a value from target, and propagates exceptions back to the main thread when this value is collected.

The output method joins the thread, then checks for errors and returns the output value.

so, if you have a function f where f(1, 2, a=3) == 4, then:

>>> thread = RespondingThread(target=f, args=(1, 2), kwargs={'a': 3})
>>> thread.start()
>>> # do other things while this is running
>>> out = thread.output()  # out is 4

This constructor should always be called with keyword arguments. Arguments are:

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

args is a list or tuple of arguments for the target invocation. Defaults to ().

kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.

Methods:

run()

Method representing the thread's activity.

output([timeout])

run() None[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

output(timeout: float | None = None) T | None[source]
qcodes.utils.attribute_set_to(object_: object, attribute_name: str, new_value: Any) Iterator[None][source]

This context manager allows to change a given attribute of a given object to a new value, and the original value is reverted upon exit of the context manager.

Parameters:
  • object – The object which attribute value is to be changed.

  • attribute_name – The name of the attribute that is to be changed.

  • new_value – The new value to which the attribute of the object is to be changed.

qcodes.utils.checked_getattr(instance: Any, attribute: str, expected_type: type | tuple[type, ...]) Any[source]

Like getattr but raises type error if not of expected type.

qcodes.utils.checked_getattr_indexed(instance: Any, attribute: str, expected_type: type | tuple[type, ...]) Any[source]

Like getattr_indexed but raises type error if not of expected type.

qcodes.utils.convert_legacy_version_to_supported_version(ver: str) str[source]

Convert a legacy version str containing single chars rather than numbers to a regular version string. This is done by replacing a char by its ASCII code (using ord). This assumes that the version number only uses at most a single char per level and only ASCII chars.

It also splits off anything that comes after the first - in the version str.

This is meant to pass versions like 'A.02.17-02.40-02.17-00.52-04-01' primarily used by Keysight instruments.

qcodes.utils.deep_update(dest: MutableMapping[K, Any], update: Mapping[L, Any]) MutableMapping[K | L, Any][source]

Recursively update one JSON structure with another.

Only dives into nested dicts; lists get replaced completely. If the original value is a dictionary and the new value is not, or vice versa, we also replace the value completely.

qcodes.utils.deprecate(reason: str | None = None, alternative: str | None = None) Callable[[...], Any][source]

A utility function to decorate deprecated functions and classes.

Note that this is not recommended to be used for deprecation any new code. It is recommended to use typing_extensions.deprecated (which will be added to the std lib as warnings.deprecated in python 3.13)

Parameters:
  • reason – The reason of deprecation.

  • alternative – The alternative function or class to put in use instead of the deprecated one.

qcodes.utils.diff_param_values(left_snapshot: dict[str, Any], right_snapshot: dict[str, Any]) ParameterDiff[source]

Given two snapshots, returns the differences between parameter values in each.

qcodes.utils.extract_param_values(snapshot: dict[str, Any]) dict[str | tuple[str, str], Any][source]

Given a snapshot, returns a dictionary from instrument and parameter names onto parameter values.

qcodes.utils.full_class(obj: object) str[source]

The full importable path to an object’s class.

qcodes.utils.get_all_installed_package_versions() dict[str, str][source]

Return a dictionary of the currently installed packages and their versions.

qcodes.utils.get_qcodes_path(*subfolder: str) str[source]

Return full file path of the QCoDeS module. Additional arguments will be appended as subfolder.

qcodes.utils.get_qcodes_user_path(*file_parts: str) str[source]

Get ~/.qcodes path or if defined the path defined in the QCODES_USER_PATH environment variable.

Returns:

path to the user qcodes directory

qcodes.utils.getattr_indexed(instance: Any, attribute: str) Any[source]

Similar to getattr but allows indexing the returned attribute. Returning a default value is _not_ supported.

The indices are decimal digits surrounded by square brackets. Chained indexing is supported, but the string should not contain any whitespace between consecutive indices.

Example: getattr_indexed(some_object, “list_of_lists_field[1][2]”)

qcodes.utils.is_function(f: object, arg_count: int, coroutine: bool = False) bool[source]

Check and require a function that can accept the specified number of positional arguments, which either is or is not a coroutine type casting “functions” are allowed, but only in the 1-argument form.

Parameters:
  • f – Function to check.

  • arg_count – Number of argument f should accept.

  • coroutine – Is a coroutine.

Returns:

is function and accepts the specified number of arguments.

Return type:

bool

qcodes.utils.is_qcodes_installed_editably() bool | None[source]

Try to ask pip whether QCoDeS is installed in editable mode and return the answer a boolean. Returns None if pip somehow did not respond as expected.

qcodes.utils.issue_deprecation_warning(what: str, reason: str | None = None, alternative: str | None = None, stacklevel: int = 3) None[source]

Issue a QCoDeSDeprecationWarning with a consistently formatted message

qcodes.utils.list_of_data_to_maybe_ragged_nd_array(column_data: Sequence[Any], dtype: type | None = None) np.ndarray[source]

Convert a (nested) Sequence of data to numpy arrays. Handle that the elements of the sequence may not have the same length in which case the returned array will be of dtype object.

qcodes.utils.partial_with_docstring(func: Callable[..., Any], docstring: str, **kwargs: Any) Callable[..., Any][source]

We want to have a partial function which will allow us to access the docstring through the python built-in help function. This is particularly important for client-facing driver methods, whose arguments might not be obvious.

Consider the follow example why this is needed:

>>> from functools import partial
>>> def f():
>>> ... pass
>>> g = partial(f)
>>> g.__doc__ = "bla"
>>> help(g) # this will print the docstring of partial and not the docstring set above
Parameters:
  • func – A function that its docstring will be accessed.

  • docstring – The docstring of the corresponding function.

  • **kwargs – Keyword arguments passed to the function.

qcodes.utils.qcodes_abstractmethod(funcobj: Callable[input, output]) Callable[input, output][source]

A decorator indicating abstract methods.

This is heavily inspired by the decorator of the same name in the ABC standard library. But we make our own version because we actually want to allow the class with the abstract method to be instantiated and we will use this property to detect if the method is abstract and should be overwritten.

qcodes.utils.strip_attrs(obj: object, whitelist: Sequence[str] = ()) None[source]

Irreversibly remove all direct instance attributes of object, to help with disposal, breaking circular references.

Parameters:
  • obj – Object to be stripped.

  • whitelist – List of names that are not stripped from the object.

qcodes.utils.thread_map(callables: Sequence[Callable[..., T]], args: Sequence[Sequence[Any]] | None = None, kwargs: Sequence[dict[str, Any]] | None = None) list[T | None][source]

Evaluate a sequence of callables in separate threads, returning a list of their return values.

Parameters:
  • callables – A sequence of callables.

  • args (Optional) – A sequence of sequences containing the positional arguments for each callable.

  • kwargs (Optional) – A sequence of dicts containing the keyword arguments for each callable.