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_unique_attr(obj, name, value, check_dup=False)[source]¶
Create an attribute if the attribute name isn’t already used.
- Parameters:
- 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.
- 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.
- 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.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.
- 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:
- Returns:
A linear list of all the indices made up only of numbers and strings.
- Return type:
- Raises:
IndexError – If a slice index is out of valid range.
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- skidl.utilities.fullmatch(regex, string, flags=0)[source]¶
Emulate python-3.4 re.fullmatch() function.
- 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:
- 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:
- Returns:
A unique name that doesn’t exist in the list.
- Return type:
- skidl.utilities.is_binary_file(filename)[source]¶
Return true if a file contains binary (non-text) characters.
- 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.
- 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.
- 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.
- 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_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.
- 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.