qcodes.utils.helpers

class qcodes.utils.helpers.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).

delegate_attr_dicts: 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: 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: List[str] = []

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

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

Bases: json.encoder.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 OverflowError). 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.

default(obj: 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).

encode(o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
item_separator = ', '
iterencode(o, _one_shot=False)

Encode the given object and yield each string representation as available.

For example:

for chunk in JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)
key_separator = ': '
qcodes.utils.helpers.abstractmethod(funcobj: Callable[[...], Any]) Callable[[...], Any][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.helpers.add_to_spyder_UMR_excludelist(modulename: str) None[source]

Spyder tries to reload any user module. This does not work well for qcodes because it overwrites Class variables. QCoDeS uses these to store global attributes such as default station, monitor and list of instruments. This “feature” can be disabled by the gui. Unfortunately this cannot be disabled in a natural way programmatically so in this hack we replace the global __umr__ instance with a new one containing the module we want to exclude. This will do nothing if Spyder is not found. TODO is there a better way to detect if we are in spyder?

qcodes.utils.helpers.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.helpers.checked_getattr(instance: Any, attribute: str, expected_type: Union[type, Tuple[type, ...]]) Any[source]

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

qcodes.utils.helpers.compare_dictionaries(dict_1: Dict[Hashable, Any], dict_2: Dict[Hashable, Any], dict_1_name: Optional[str] = 'd1', dict_2_name: Optional[str] = 'd2', path: str = '') Tuple[bool, str][source]

Compare two dictionaries recursively to find non matching elements.

Parameters
  • dict_1 – First dictionary to compare.

  • dict_2 – Second dictionary to compare.

  • dict_1_name – Optional name of the first dictionary used in the differences string.

  • dict_2_name – Optional name of the second dictionary used in the differences string.

Returns

Are the dicts equal and the difference rendered as

a string.

Return type

Tuple

qcodes.utils.helpers.create_on_off_val_mapping(on_val: Any = True, off_val: Any = False) Dict[Union[str, bool], Any][source]

Returns a value mapping which maps inputs which reasonably mean “on”/”off” to the specified on_val/off_val which are to be sent to the instrument. This value mapping is such that, when inverted, on_val/off_val are mapped to boolean True/False.

qcodes.utils.helpers.deep_update(dest: MutableMapping[qcodes.utils.helpers.K, Any], update: Mapping[qcodes.utils.helpers.L, Any]) MutableMapping[Union[qcodes.utils.helpers.K, qcodes.utils.helpers.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.helpers.foreground_qt_window(window: QMainWindow) None[source]

Try as hard as possible to bring a qt window to the front. This will use pywin32 if installed and running on windows as this seems to be the only reliable way to foreground a window. The build-in qt functions often doesn’t work. Note that to use this with pyqtgraphs remote process you should use the ref in that module as in the example below.

Parameters

window – Handle to qt window to foreground.

Examples

>>> Qtplot.qt_helpers.foreground_qt_window(plot.win)
qcodes.utils.helpers.full_class(obj: object) str[source]

The full importable path to an object’s class.

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

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

qcodes.utils.helpers.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.helpers.is_function(f: Callable[[...], Any], 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.helpers.is_sequence(obj: Any) bool[source]

Test if an object is a sequence.

We do not consider strings or unordered collections like sets to be sequences, but we do accept iterators (such as generators).

qcodes.utils.helpers.is_sequence_of(obj: Any, types: Optional[Union[Type[object], Tuple[Type[object], ...]]] = None, depth: Optional[int] = None, shape: Optional[Sequence[int]] = None) bool[source]

Test if object is a sequence of entirely certain class(es).

Parameters
  • obj – The object to test.

  • types – Allowed type(s). If omitted, we just test the depth/shape.

  • depth – Level of nesting, ie if depth=2 we expect a sequence of sequences. Default 1 unless shape is supplied.

  • shape – The shape of the sequence, ie its length in each dimension. If depth is omitted, but shape included, we set depth = len(shape).

Returns

True if every item in obj matches types.

Return type

bool

qcodes.utils.helpers.make_sweep(start: float, stop: float, step: Optional[float] = None, num: Optional[int] = None) List[float][source]

Generate numbers over a specified interval. Requires start and stop and (step or num). The sign of step is not relevant.

Parameters
  • start – The starting value of the sequence.

  • stop – The end value of the sequence.

  • step – Spacing between values.

  • num – Number of values to generate.

Returns

numbers over a specified interval as a numpy.linspace.

Return type

numpy.ndarray

Examples

>>> make_sweep(0, 10, num=5)
[0.0, 2.5, 5.0, 7.5, 10.0]
>>> make_sweep(5, 10, step=1)
[5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
>>> make_sweep(15, 10.5, step=1.5)
>[15.0, 13.5, 12.0, 10.5]
qcodes.utils.helpers.named_repr(obj: Any) str[source]

Enhance the standard repr() with the object’s name attribute.

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

We want to have a partial function which will allow us 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 an unhelpful message
Parameters
  • func – A function that its docstring will be accessed.

  • docstring – The docstring of the corresponding function.

qcodes.utils.helpers.permissive_range(start: float, stop: float, step: SupportsAbs[float]) List[float][source]

Returns a range (as a list of values) with floating point steps. Always starts at start and moves toward stop, regardless of the sign of step.

Parameters
  • start – The starting value of the range.

  • stop – The end value of the range.

  • step – Spacing between the values.

qcodes.utils.helpers.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.helpers.tprint(string: str, dt: int = 1, tag: str = 'default') None[source]

Print progress of a loop every dt seconds.

qcodes.utils.helpers.wait_secs(finish_clock: float) float[source]

Calculate the number of seconds until a given clock time. The clock time should be the result of time.perf_counter(). Does NOT wait for this time.

qcodes.utils.helpers.warn_units(class_name: str, instance: object) None[source]