hbutils.reflection.iter
This module provides utilities for creating nested and progressive iteration patterns.
It includes functions for generating nested for-loops from multiple iterables and progressive for-loops from a single iterable with configurable depth and offset.
nested_for
- hbutils.reflection.iter.nested_for(*iters: Iterable[_ItemType]) Iterator[Tuple[_ItemType, ...]][source]
Create a nested for-loop based on several iterators.
This function generates all possible combinations by iterating through multiple iterables in a nested manner, similar to nested for-loops.
- Parameters:
iters (Iterable[_ItemType]) – Variable number of iterables to build the nested for loop.
- Returns:
Iterator yielding tuples containing one element from each iterable.
- Return type:
Iterator[Tuple[_ItemType, …]]
- Examples::
>>> from hbutils.reflection import nested_for >>> for a, r, b in nested_for( ... range(1, 3), ... ['a', 'b'], ... map(lambda x: x ** 2, range(1, 4)) ... ): ... print(a, r, b) 1 a 1 1 a 4 1 a 9 1 b 1 1 b 4 1 b 9 2 a 1 2 a 4 2 a 9 2 b 1 2 b 4 2 b 9
progressive_for
- hbutils.reflection.iter.progressive_for(iterable: Iterable[_ItemType], n: int, offset: int = 1) Iterator[Tuple[_ItemType, ...]][source]
Create a progressive for-loop based on one given iterable.
This function generates combinations where each subsequent level starts from a position relative to the previous level’s selection, determined by the offset parameter.
- Parameters:
iterable (Iterable[_ItemType]) – Iterable object for this loop.
n (int) – Depth of this loop (number of nested levels).
offset (int) – Offset of this loop, default is
1which means the first value in the next level will be the one after the above level. An offset of 0 means the next level can start from the same position as the current level.
- Returns:
Iterator yielding tuples of progressively selected items.
- Return type:
Iterator[Tuple[_ItemType, …]]
- Raises:
ValueError – If offset is negative.
- Examples::
>>> from hbutils.reflection import progressive_for >>> for a, b in progressive_for(range(4), 2): ... print(a, b) 0 1 0 2 0 3 1 2 1 3 2 3 >>> for a, b in progressive_for(range(4), 2, 0): ... print(a, b) 0 0 0 1 0 2 0 3 1 1 1 2 1 3 2 2 2 3 3 3 >>> for a, b, c in progressive_for(range(5), 3): ... print(a, b, c) 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 >>> for a, b, c in progressive_for(range(5), 3, 2): ... print(a, b, c) 0 2 4