8.5.23. pymodaq_utils.utils module

exception pymodaq_utils.utils.UnsafeExpressionError[source]

Bases: ValueError

Raised when the text of a stored value is anything else than a plain value

class pymodaq_utils.utils.JsonConverter[source]

Bases: object

Convert simple python objects to and from a json string

The json string holds the module, type and repr of the object. Only the types listed in trusted_types() are rebuilt when converting back.

Methods

istrusted(type_name)

Return True if type_name is one of the trusted_types()

json2object(jsonstring)

Rebuild an object from the json string created by object2json()

object2json(obj)

Return a json string with the module, type name and repr of obj

trusted_types()

Names of the types json2object() is allowed to rebuild

classmethod istrusted(type_name)[source]

Return True if type_name is one of the trusted_types()

Return type:

bool

classmethod json2object(jsonstring)[source]

Rebuild an object from the json string created by object2json()

Returns:

The object if its type is trusted, otherwise the decoded dict. If jsonstring cannot be decoded, it is returned unchanged.

Return type:

Any

classmethod object2json(obj)[source]

Return a json string with the module, type name and repr of obj

Return type:

str

classmethod trusted_types()[source]

Names of the types json2object() is allowed to rebuild

Return type:

list[str]

class pymodaq_utils.utils.ThreadCommand(command, attribute=None, attributes=None, args=(), kwargs=None)[source]

Bases: SerializableBase

Generic object to pass info (command) and data (attribute) between thread or objects using signals

Parameters:
  • command (str) – The command to be analysed for further action

  • attribute (any type) – the attribute related to the command. The actual type and value depend on the command and the situation

  • attributes (deprecated, attribute should be used instead)

Variables:
  • command (str) – The command to be analysed for further action

  • attribute (any type) – the attribute related to the command. The actual type and value depend on the command and the situation

  • args (some variables in a list)

  • kwargs (some variables in a dict)

Methods

deserialize(bytes_str)

Rebuild a ThreadCommand from bytes created by serialize()

serialize(obj)

Serialize the command, attribute, args and kwargs of a ThreadCommand into bytes

static deserialize(bytes_str)[source]

Rebuild a ThreadCommand from bytes created by serialize()

Returns:

The ThreadCommand and the remaining bytes that were not consumed.

Return type:

Tuple[ThreadCommand, bytes]

static serialize(obj)[source]

Serialize the command, attribute, args and kwargs of a ThreadCommand into bytes

Return type:

bytes

args: list
attribute: Any
command: str
kwargs: dict
pymodaq_utils.utils.caller_name(skip=2)[source]

Get a name of a caller in the format module.class.method

skip specifies how many levels of stack to skip while getting caller name. skip=1 means “who calls me”, skip=2 “who calls my caller” etc.

An empty string is returned if skipped levels exceed stack height

pymodaq_utils.utils.capitalize(string, Nfirst=1)[source]

Returns same string but with first Nfirst letters upper :param string: :type string: (str) :param Nfirst: :type Nfirst: (int)

Return type:

str

pymodaq_utils.utils.check_vals_in_iterable(iterable1, iterable2)[source]

Assert that two iterables (list, tuple, ndarray…) have the same length and equal values

Return type:

None

pymodaq_utils.utils.count_lines(ini_path, count=0, filters=['lextab', 'yacctab', 'pycache', 'pyc'])[source]

Count the lines of the python files below ini_path, starting from count

The names of the files skipped because of filters are printed.

pymodaq_utils.utils.elt_as_first_element(elt_list, match_word='Mock')[source]

Return a list of str with the first one containing match_word moved to the front

The first element is kept in front if none matches. Note that the matching element is removed from elt_list itself, which is modified.

Raises:

TypeError – If elt_list is not an iterable of str.

pymodaq_utils.utils.elt_as_first_element_dicts(elt_list, match_word='Mock', key='name')[source]

Same as elt_as_first_element() for a list of dicts, matching match_word in elt[key]

Raises:

TypeError – If elt_list is not an iterable of dict.

pymodaq_utils.utils.ensure_ndarray(data)[source]

Make sure data is returned as a numpy array :type data: :param data:

Return type:

ndarray

pymodaq_utils.utils.find_dict_if_matched_key_val(dict_tmp, key, value)[source]

check if a key/value pair match in a given dictionary :param dict_tmp: :type dict_tmp: (dict) the dictionary to be tested :param key: :type key: (str) a key string to look for in dict_tmp :param value: :type value: (object) any python object

Returns:

bool

Return type:

True if the key/value pair has been found in dict_tmp

pymodaq_utils.utils.find_dict_in_list_from_key_val(dicts, key, value, return_index=False)[source]

lookup within a list of dicts. Look for the dict within the list which has the correct key, value pair

Parameters:
  • dicts ((list) list of dictionnaries)

  • key ((str) specific key to look for in each dict)

  • value (value to match)

Returns:

dict

Return type:

if found otherwise returns None

pymodaq_utils.utils.find_dicts_in_list_from_key_val(dicts, key, value)[source]

lookup within a list of dicts. Look for the dicts within the list which have the correct key, value pair

Parameters:
  • dicts ((list) list of dictionnaries)

  • key ((str) specific key to look for in each dict)

  • value (value to match)

Returns:

dict

Return type:

if found otherwise returns None

pymodaq_utils.utils.find_keys_from_val(dict_tmp, val)[source]

Returns the keys from a dict if its value is matching val

Return type:

list

pymodaq_utils.utils.find_object_if_matched_attr_name_val(obj, attr_name, attr_value)[source]

check if an attribute key/value pair match in a given object

Parameters:
  • obj (object)

  • attr_name (str) – attribute name to look for in the object

  • attr_value (object) – value to match

Returns:

bool

Return type:

True if the key/value pair has been found in dict_tmp

pymodaq_utils.utils.find_objects_in_list_from_attr_name_val(objects, attr_name, attr_value, return_first=True)[source]

lookup within a list of objects. Look for the objects within the list which has the correct attribute name, value pair

Parameters:
  • objects (Sequence[Any]) – list of objects

  • attr_name (str) – attribute name to look for in the object

  • attr_value (object) – value to match

  • return_first (bool) – if True return the first objects found in the list else all the objects matching

Returns:

list of tuple(object, int)

Return type:

object and index or list of object and indexes

pymodaq_utils.utils.format_dir_path(path)[source]

Return path as a str, with the separator of the OS appended if it is an existing folder

Return type:

str

pymodaq_utils.utils.getLineInfo()[source]

get information about where the Exception has been triggered

pymodaq_utils.utils.get_entrypoints(group='pymodaq.plugins')[source]

Get the list of modules defined from a group entry point

Because of evolution in the package, one or another of the forms below may be deprecated. We start from the newer way down to the older

Parameters:

group (str) – the name of the group

Return type:

List[EntryPoint]

pymodaq_utils.utils.get_module_path(module_name)[source]

Get Path of a given module represented by its name

You get the name usually with the dunder __module__ on an object or class

Raises:

TypeError – If the module has no file (namespace package or built-in module)

Return type:

Path

pymodaq_utils.utils.get_new_file_name(base_path, base_name='tttr_data')[source]

Get the name of a new file in the folder <base_path>/<year>/<date> (created if needed)

Returns:

The file name without extension, <base_name>_NNN with NNN the index following the last existing file starting with base_name in the folder, and the path of the folder.

Return type:

Tuple[str, Path]

pymodaq_utils.utils.get_version(package_name='pymodaq')[source]

Obtain the package version using the importlib metadata module

pymodaq_utils.utils.is_64bits()[source]

Return True if the running Python interpreter is a 64 bits one

Return type:

bool

pymodaq_utils.utils.read_binary_and_deserialize(fname)[source]

Deserialize all the objects stored one after the other in a binary file

Returns an empty list if the file does not exist.

Return type:

list[SerializableBase]

pymodaq_utils.utils.recursive_find_expr_in_files(ini_path, exp='make_enum', paths=[], filters=['.git', '.idea', '__pycache__', 'build', 'egg', 'documentation', '.tox'], replace=False, replace_str='')[source]

Search the text exp in the files below ini_path

Each match is appended to paths as [file path, line index, line]. Paths containing one of the filters strings are skipped and unreadable files are ignored. If replace is True the matches are replaced in the files by replace_str. As in recursive_find_files_extension(), pass a new list as paths.

pymodaq_utils.utils.recursive_find_files(ini_path, exp='make_enum', paths=[], filters=['build'])[source]

Collect the paths of all files below ini_path whose name (without extension) contains exp

Paths containing one of the filters strings are skipped. As in recursive_find_files_extension(), pass a new list as paths.

pymodaq_utils.utils.recursive_find_files_extension(ini_path, ext, paths=[])[source]

Collect the paths of all files with the extension ext (without dot) below ini_path

Note that paths is shared between calls when not given (mutable default): pass a new list.

pymodaq_utils.utils.remove_spaces(string)[source]

return a string without any white spaces in it :type string: :param string:

pymodaq_utils.utils.rint(x)[source]

almost same as numpy rint function but return an integer :param x: :type x: (float or integer)

Return type:

nearest integer

pymodaq_utils.utils.safe_literal_eval(text)[source]

Equivalent of eval for the repr of the values stored by JsonConverter, that cannot run code

Return type:

Any

pymodaq_utils.utils.timer(func)[source]

Print the runtime of the decorated function

pymodaq_utils.utils.uncapitalize(string, Nfirst=1)[source]

Return the same string but with its first Nfirst letters in lower case

Return type:

str

pymodaq_utils.utils.zeros_aligned(n, align, dtype=<class 'numpy.uint32'>)[source]

Get aligned memory array wih alignment align. :param n: :type n: (int) length in dtype bytes of memory :param align: :type align: (int) memory alignment :param dtype: :type dtype: (numpy.dtype) type of the stored memory elements