skidl.utilities module

Utility functions used by the rest of SKiDL.

This module provides various helper functions and classes that support the main SKiDL functionality, including string manipulation, list operations, file handling, and other utility operations.

class skidl.utilities.Rgx(s)[source]

Bases: str

String subclass that represents a regular expression.

This class is used to distinguish regular expressions from normal strings in functions that need to process both types differently.

class skidl.utilities.TriggerDict(*args, **kwargs)[source]

Bases: dict

Dictionary that triggers a function when one of its entries changes.

This dictionary subclass allows custom functions to be executed when specific keys are modified.

skidl.utilities.add_quotes(s)[source]

Return string with added quotes using JSON formatting.

Parameters:

s (str or other) – Input string or non-string object.

Returns:

String with quotes added, or the original object if not a string.

Return type:

str or other

skidl.utilities.add_unique_attr(obj, name, value, check_dup=False)[source]

Create an attribute if the attribute name isn’t already used.

Parameters:
  • obj – Object to which the attribute will be added.

  • name (str) – Name of the attribute to add.

  • value – Value to assign to the attribute.

  • check_dup (bool, optional) – If True, warns if attribute already exists but doesn’t modify it. If False, overwrites existing attribute. Defaults to False.

skidl.utilities.cnvt_to_var_name(s)[source]

Convert a string to a legal Python variable name.

Replaces illegal characters with underscores to create a valid Python identifier.

Parameters:

s (str) – The string to convert.

Returns:

A valid Python variable name.

Return type:

str

skidl.utilities.consistent_hash(text)[source]

Return a hash value for a text string.

This function generates a deterministic, consistent hash value for a given string using SHA-256 algorithm.

Parameters:

text (str) – The input string to hash.

Returns:

A 16-character hexadecimal hash string.

Return type:

str

skidl.utilities.debug_trace(fn, *args, **kwargs)[source]

Decorator to print tracing info when debugging execution.

When the decorated function is called with debug_trace=True, it will print the function name before execution.

Parameters:
  • fn (function) – The function to be decorated.

  • *args – Variable length argument list.

  • **kwargs – Arbitrary keyword arguments.

Returns:

The decorated function.

Return type:

function

skidl.utilities.detect_os()[source]

Detect the operating system.

Returns:

The name of the operating system (‘Windows’, ‘Linux’, or ‘MacOS’).

Return type:

str

Raises:

Exception – If the operating system cannot be identified.

skidl.utilities.expand_buses(pins_nets_buses)[source]

Take list of pins, nets, and buses and return a list of only pins and nets.

This function flattens a list containing both buses and their nets/pins into a flat list of just nets/pins.

Parameters:

pins_nets_buses (list) – List containing pins, nets, and buses.

Returns:

A flattened list containing only pins and nets.

Return type:

list

skidl.utilities.expand_indices(slice_min, slice_max, match_regex, *indices)[source]

Expand a list of indices into a list of integers and strings.

This function takes the indices used to select pins of parts and lines of buses and returns a flat list of numbers and strings. String and integer indices are put in the list unchanged, but slices are expanded into a list of integers before entering the final list. It also handles bus notation expressions.

Parameters:
  • slice_min (int) – The minimum possible index.

  • slice_max (int) – The maximum possible index (used for slice indices).

  • match_regex (bool) – If true, adjust regex patterns for pin/bus matches.

  • *indices – A list of indices made up of numbers, slices, text strings.

Returns:

A linear list of all the indices made up only of numbers and strings.

Return type:

list

Raises:

IndexError – If a slice index is out of valid range.

skidl.utilities.expand_path(path)[source]
skidl.utilities.export_to_all(fn)[source]

Add a function to the __all__ list of this module.

This decorator adds the decorated function’s name to the module’s __all__ list, making it available when using “from module import *”.

Parameters:

fn (function) – The function to be added to the __all__ list of this module.

Returns:

The function that was passed in, unchanged.

Return type:

function

skidl.utilities.filter_list(lst, **criteria)[source]

Return a list of objects whose attributes match a set of criteria.

This function filters a list based on attribute values using regular expressions.

Example: filter_list(pins, name=’io[0-9]+’, direction=’bidir’) will return all the bidirectional pins of the component that have pin names starting with ‘io’ followed by a number (e.g., ‘IO45’).

If an attribute of the lst object is a list or tuple, each entry in the list/tuple will be checked for a match. Only one entry needs to match to consider the entire attribute a match. This feature is useful when searching for objects that contain a list of aliases, such as Part objects.

Parameters:

lst – The list from which objects will be extracted.

Keyword Arguments:

criteria

Keyword-argument pairs. The keyword specifies the attribute name while the argument contains the desired value of the attribute. Regardless of what type the argument is, it is always compared as if it was a string. The argument can also be a regular expression that must match the entire string created from the attribute of the list object.

Special keyword ‘do_str_match’: If True, use string matching instead of regex.

Returns:

A list of objects whose attributes match all the criteria.

Return type:

list

skidl.utilities.find_and_open_file(filename, paths=None, ext=None, allow_failure=False, exclude_binary=False, descend=0)[source]

Search for a file in list of paths, open it and return file pointer and full file name.

This function searches for a file in various locations, including URLs, and returns an open file pointer and the complete path to the file.

Parameters:
  • filename (str) – Base file name (e.g., “my_file”).

  • paths (list, optional) – List of paths to search for the file. Defaults to current directory.

  • ext (str or list, optional) – The extension for the file (e.g., “.txt”) or a list of extensions.

  • allow_failure (bool, optional) – If False, failure to find file raises an exception. Defaults to False.

  • exclude_binary (bool, optional) – If True, skip files that contain binary data. Defaults to False.

  • descend (int, optional) – If 0, don’t search lower-level directories. If positive, search that many levels down for the file. If negative, descend into subdirectories without limit. Defaults to 0.

Returns:

(file_pointer, file_name) or (None, None) if file could not be opened and allow_failure is True.

Return type:

tuple

Raises:

FileNotFoundError – If the file couldn’t be found and allow_failure is False.

skidl.utilities.find_and_read_file(filename, paths=None, ext=None, allow_failure=False, exclude_binary=False, descend=0)[source]

Search for a file in list of paths, open it and return its contents.

Parameters:
  • filename (str) – Base file name (e.g., “my_file”).

  • paths (list, optional) – List of paths to search for the file. Defaults to current directory.

  • ext (str or list, optional) – The extension for the file (e.g., “.txt”) or a list of extensions.

  • allow_failure (bool, optional) – If False, failure to find file raises an exception. Defaults to False.

  • exclude_binary (bool, optional) – If True, skip files that contain binary data. Defaults to False.

  • descend (int, optional) – If 0, don’t search lower-level directories. If positive, search that many levels down for the file. If negative, descend into subdirectories without limit. Defaults to 0.

Returns:

(file_contents, file_name) or (None, None) if file could not be opened and allow_failure is True.

Return type:

tuple

Raises:

FileNotFoundError – If the file couldn’t be found and allow_failure is False.

skidl.utilities.find_num_copies(**attribs)[source]

Return the number of copies to make based on the number of attribute values.

This function examines keyword arguments to determine how many copies of an object should be created. If all values are scalar or lists/tuples of length 1, only one copy is needed. If there are lists/tuples of greater length, the maximum length determines the number of copies.

Keyword Arguments:

attribs – Dict of Keyword/Value pairs for setting object attributes. If the value is a scalar, then the number of copies is one. If the value is a list/tuple, the number of copies is the length of the list/tuple.

Returns:

The length of the longest value in the dict of attributes.

Return type:

int

Raises:
  • ValueError – If there are two or more list/tuple values with different

  • lengths that are greater than 1. (All attribute values must be scalars

  • or lists/tuples of the same length.)

skidl.utilities.flatten(nested_list)[source]

Recursively flatten a nested list structure.

Parameters:

nested_list – A list that may contain other lists, tuples, or sets as items.

Returns:

A flat list containing all items from the nested structure.

Return type:

list

skidl.utilities.from_iadd(objs)[source]

Check if one or more objects have the iadd_flag attribute set to True.

Parameters:

objs – A single object or list of objects to check.

Returns:

True if any object has iadd_flag set to True, False otherwise.

Return type:

bool

skidl.utilities.fullmatch(regex, string, flags=0)[source]

Emulate python-3.4 re.fullmatch() function.

Parameters:
  • regex (str) – Regular expression pattern.

  • string (str) – String to match against the pattern.

  • flags (int, optional) – Flags to pass to the regex engine. Defaults to 0.

Returns:

Match object if the string matches the pattern fully, None otherwise.

Return type:

Match object or None

skidl.utilities.get_abs_filename(filename, paths=None, ext=None, allow_failure=False, descend=0)[source]

Search for a file in list of paths, and return its absolute file name.

Parameters:
  • filename (str) – Base file name (e.g., “my_file”).

  • paths (list, optional) – List of paths to search for the file. Defaults to current directory.

  • ext (str or list, optional) – The extension for the file (e.g., “.txt”) or a list of extensions.

  • allow_failure (bool, optional) – If False, failure to find file raises an exception. Defaults to False.

  • descend (int, optional) – If 0, don’t search lower-level directories. If positive, search that many levels down for the file. If negative, descend into subdirectories without limit. Defaults to 0.

Returns:

Absolute file name if file exists, otherwise None.

Return type:

str

Raises:

FileNotFoundError – If the file couldn’t be found and allow_failure is False.

skidl.utilities.get_unique_name(lst, attrib, prefix, initial=None)[source]

Generate a unique name within a list of objects.

This function is used to generate unique part references (e.g., “R12”) or unique net names (e.g., “N$5”) that don’t collide with existing names.

Parameters:
  • lst – The list of objects containing names.

  • attrib (str) – The attribute in each object containing the name.

  • prefix (str) – The prefix attached to each name.

  • initial – The initial setting of the name (can be None or empty string).

Returns:

A unique name that doesn’t exist in the list.

Return type:

str

skidl.utilities.is_binary_file(filename)[source]

Return true if a file contains binary (non-text) characters.

Parameters:

filename (str) – Path to the file to check.

Returns:

True if the file contains binary data, False otherwise.

Return type:

bool

skidl.utilities.is_url(s)[source]

Check if a string is a valid HTTP/HTTPS URL.

Parameters:

s (str) – String to check.

Returns:

True if the string is a valid HTTP/HTTPS URL, False otherwise.

Return type:

bool

skidl.utilities.list_or_scalar(lst)[source]

Return a list or scalar depending on the input.

Parameters:

lst – Either a list/tuple or a scalar value.

Returns:

  • A list if passed a multi-element list.

  • The list element if passed a single-element list.

  • None if passed an empty list.

  • A scalar if passed a scalar.

skidl.utilities.merge_dicts(dct, merge_dct)[source]

Recursively merge two dictionaries, updating keys in the first with values from the second.

This function modifies the first dictionary in-place to include keys from the second. If a key exists in both dictionaries and both values are dictionaries, it recursively merges those nested dictionaries.

Parameters:
  • dct (dict) – The target dictionary that will be updated.

  • merge_dct (dict) – The dictionary whose values will be merged into dct.

Returns:

Nothing. The first dictionary is modified in-place.

skidl.utilities.norecurse(f)[source]

Decorator that keeps a function from recursively calling itself.

This decorator checks the call stack to prevent recursive calls to the decorated function.

Parameters:

f (function) – The function to decorate.

Returns:

A wrapper function that checks for recursion.

Return type:

function

skidl.utilities.num_to_chars(num)[source]

Convert a number to a spreadsheet-style column identifier.

Parameters:

num (int) – A positive integer.

Returns:

A string like ‘A’ for 1, ‘B’ for 2, ‘Z’ for 26, ‘AA’ for 27, etc.

Return type:

str

skidl.utilities.opened(f_or_fn, mode)[source]

Context manager that yields an opened file or file-like object.

This context manager handles both filenames and file objects, ensuring proper opening and closing of files.

Parameters:
  • f_or_fn – Either an already opened file or file-like object, or a filename to open.

  • mode (str) – The mode to open the file in.

Yields:

file – An opened file object.

Raises:

TypeError – If f_or_fn is neither a string nor a file-like object.

skidl.utilities.reset_get_unique_name()[source]

Reset the heaps that store previously-assigned names.

This function clears the internal storage used by get_unique_name() to track previously generated names.

skidl.utilities.rmv_attr(objs, attrs)[source]

Remove one or more attributes from one or more objects.

Parameters:
  • objs – A single object or list of objects.

  • attrs – A string or list of strings naming attributes to remove.

skidl.utilities.rmv_iadd(objs)[source]

Remove the iadd_flag attribute from one or more objects.

Parameters:

objs – A single object or list of objects.

skidl.utilities.rmv_quotes(s)[source]

Remove starting and ending quotes from a string.

Parameters:

s (str or other) – Input string or non-string object.

Returns:

String with quotes removed, or the original object if not a string.

Return type:

str or other

skidl.utilities.rmv_unique_name(lst, attrib, name)[source]

Remove a unique name from the heap.

This function is used to remove a name that was previously generated by get_unique_name() when it is no longer needed.

Parameters:
  • lst – The list of objects containing names.

  • attrib (str) – The attribute in each object containing the name.

  • name (str) – The name to remove from the heap.

skidl.utilities.set_attr(objs, attr, value)[source]

Set an attribute to a value in one or more objects.

Parameters:
  • objs – A single object or list of objects.

  • attr (str) – Name of the attribute to set.

  • value – Value to assign to the attribute.

skidl.utilities.set_iadd(objs, value)[source]

Set the iadd_flag attribute in one or more objects.

Parameters:
  • objs – A single object or list of objects.

  • value (bool) – Value to assign to the iadd_flag attribute.

skidl.utilities.sgn(x)[source]

Return the sign of a number.

Parameters:

x (numeric) – The number to check.

Returns:

-1 if x<0, 1 if x>0, 0 if x==0.

Return type:

int

skidl.utilities.to_list(x)[source]

Convert a scalar value to a list or return x if it is already a list-like object.

Parameters:

x – Input value (scalar or list-like).

Returns:

The original list-like input or a new list containing the scalar value.

Return type:

list, tuple, or set