🧰 collections#

This module provides utilities for collection manipulation:

import stouputils as stp

# Remove duplicates, keeping the first occurrence of each value
stp.info(stp.unique_list([3, 1, 3, 2, 1]))

# Are at least 2 of these files Python files?
def is_python_file(name: str) -> bool:
    return name.endswith(".py")

stp.info(stp.at_least_n(["a.py", "b.txt", "c.py"], is_python_file, n=2))

# Put the keys of a dictionary in a chosen order
settings = {"lr": 0.1, "seed": 42, "model": "resnet"}
stp.info(stp.sort_dict_keys(settings, order=["model", "lr", "seed"]))

# Shuffle the numbers 0 to 9, the same way every time for a given seed
stp.info(list(stp.affine_permutation_generator(10, seed=7)))

# Register functions under their name, then call one by its name
MODELS = stp.Registry()

@MODELS.register
def resnet() -> str:
    return "ResNet-50"

stp.info(MODELS["resnet"]())
Terminal output of the example

dataframe#

upsert_in_dataframe(
df: pl.DataFrame,
new_entry: dict[str, Any],
primary_keys: list[str] | dict[str, Any] | None = None,
) → pl.DataFrame[source]#

Insert or update a row in the Polars DataFrame based on primary keys.

Parameters:
  • df – The Polars DataFrame to update.

  • new_entry – The new entry to insert or update.

  • primary_keys – The primary keys to identify the row (for updates).

Returns:

The updated Polars DataFrame.

>>> import polars as pl
>>> df = pl.DataFrame({"id": [1, 2], "value": ["a", "b"]})
>>> new_entry = {"id": 2, "value": "updated"}
>>> updated_df = upsert_in_dataframe(df, new_entry, primary_keys=["id"])
>>> print(updated_df)
shape: (2, 2)
β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ id  ┆ value   β”‚
β”‚ --- ┆ ---     β”‚
β”‚ i64 ┆ str     β”‚
β•žβ•β•β•β•β•β•ͺ═════════║
β”‚ 1   ┆ a       β”‚
β”‚ 2   ┆ updated β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
>>> new_entry = {"id": 3, "value": "new"}
>>> updated_df = upsert_in_dataframe(updated_df, new_entry, primary_keys=["id"])
>>> print(updated_df)
shape: (3, 2)
β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ id  ┆ value   β”‚
β”‚ --- ┆ ---     β”‚
β”‚ i64 ┆ str     β”‚
β•žβ•β•β•β•β•β•ͺ═════════║
β”‚ 1   ┆ a       β”‚
β”‚ 2   ┆ updated β”‚
β”‚ 3   ┆ new     β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

iterable#

unique_list(
list_to_clean: Iterable,
method: Literal['id', 'hash', 'str'] = 'str',
) → list[T][source]#

Remove duplicates from the list while keeping the order using ids, hash, or str

Parameters:
  • list_to_clean – The list to clean

  • method – The method to use to identify duplicates

Returns:

The cleaned list

>>> unique_list([1, 2, 3, 2, 1], method="id")
[1, 2, 3]
>>> s1 = {1, 2, 3}
>>> s2 = {2, 3, 4}
>>> s3 = {1, 2, 3}
>>> unique_list([s1, s2, s1, s1, s3, s2, s3], method="id")
[{1, 2, 3}, {2, 3, 4}, {1, 2, 3}]
>>> s1 = {1, 2, 3}
>>> s2 = {2, 3, 4}
>>> s3 = {1, 2, 3}
>>> unique_list([s1, s2, s1, s1, s3, s2, s3], method="str")
[{1, 2, 3}, {2, 3, 4}]
at_least_n(
iterable: Iterable,
predicate: Callable[[T], bool],
n: int,
) → bool[source]#

Return True if at least n elements in iterable satisfy predicate. It’s like the built-in any() but for at least n matches.

Stops iterating as soon as n matches are found (short-circuit evaluation).

Parameters:
  • iterable – The iterable to check.

  • predicate – The predicate to apply to items.

  • n – Minimum number of matches required.

Returns:

True if at least n elements satisfy predicate, otherwise False.

>>> at_least_n([1, 2, 3, 4, *[i for i in range(5, int(1e5))]], lambda x: x % 2 == 0, 2)
True
>>> at_least_n([1, 3, 5, 7], lambda x: x % 2 == 0, 1)
False

registry#

Registries map names to objects registered by decorator. They replace a hand-written dictionary kept next to the functions it lists:

def foo(bar: int) -> int:
    return bar * 5
def another_foo(bar: int) -> int:
    return bar * 2

FOO_REGISTRY: dict[str, Callable[[int], int]] = {
    "foo": foo,
    "baz": another_foo,
}

with:

FOO_REGISTRY = Registry[Callable[[int], int]]()

@FOO_REGISTRY
def foo(bar: int) -> int:
    return bar * 5

@FOO_REGISTRY(name="baz")
def another_foo(bar: int) -> int:
    return bar * 2
class Registry(
entries: SupportsKeysAndGetItem[str, T] | Iterable[tuple[str, T]] = (),
/,
*,
key_getter: Callable[[T], str] | None = None,
**kwargs: T,
)[source]#

Bases: dict[str, T], Generic

Dictionary that registers any object by decorator.

>>> FUNCS = Registry[Callable[[int], int]]()
>>> from stouputils import handle_error
>>> @FUNCS.register
... @handle_error
... def measured(value: int) -> int: return value * 5
>>> FUNCS["measured"] is measured
True
>>> FUNCS = Registry[Callable[[int], int]]()
>>> @FUNCS(name="tripled")
... def triple(value: int) -> int: return value * 3
>>> FUNCS["tripled"](4)
12
>>> class Shape:
...     @classmethod
...     def get_name(cls) -> str: return cls.__name__.lower()
>>> SHAPES = Registry[type[Shape]](key_getter=lambda cls: cls.get_name())
>>> @SHAPES.register
... class Circle(Shape): pass
>>> @SHAPES.register(name="square")
... class Square(Shape): pass
>>> sorted(SHAPES), SHAPES["circle"] is Circle
(['circle', 'square'], True)
>>> @SHAPES.register()
... class NotAShape: pass
Traceback (most recent call last):
...
AttributeError: type object 'NotAShape' has no attribute 'get_name'
>>> @SHAPES.register(name="circle")
... class Duplicate(Shape): pass
Traceback (most recent call last):
...
KeyError: "The name 'circle' is already registered."
key_getter: Callable[[T], str] | None[source]#

Callable taking an object and returning its key, or None to use the object’s name.

register(
function: T | None = None,
*,
name: str | None = None,
aliases: list[str] | None = None,
) → T | Callable[[T], T][source]#

Register any object by its own name or a custom name.

Python applies stacked decorators from bottom to top. Put register outermost when the registry should keep the fully decorated object.

shuffle#

affine_permutation_generator(
n: int,
seed: int = 0,
) → Generator[int][source]#

Generate a memory-efficient pseudo-random permutation of [0, n).

Each i in [0, n) can only be visited once thanks to the affine bijection: (a*i + b) % n where a and b are random integers and coprime with n.

Parameters:
  • n – Number of elements to visit.

  • seed – Random seed for reproducibility.

Yields:

A random permutation of [0, n).

>>> list(affine_permutation_generator(10))
[6, 3, 0, 7, 4, 1, 8, 5, 2, 9]
>>> list(affine_permutation_generator(10, seed=42))
[4, 5, 6, 7, 8, 9, 0, 1, 2, 3]

Make sure all elements are visited:

>>> sorted(list(affine_permutation_generator(100, seed=42))) == list(range(100))
True

We can have infinite permutations without blowing up memory:

>>> for i, perm in enumerate(affine_permutation_generator(100**2000)):
...     if i > 4: break
...     print(f"Permutation {i}: {str(perm)[:20]}...")
Permutation 0: 60923891346657165714...
Permutation 1: 77383182119683752460...
Permutation 2: 93842472892710339206...
Permutation 3: 10301763665736925951...
Permutation 4: 26761054438763512697...
feistel_permutation_generator(
n: int,
seed: int = 0,
) → Generator[int][source]#

Generate a memory-efficient pseudo-random permutation of [0, n).

This uses a Feistel network to build a bijective mapping over a power-of-two domain, then filters values outside [0, n).

Unlike affine permutations, this produces a much more β€œshuffle-like” order with significantly reduced algebraic structure.

Parameters:
  • n – Number of elements to visit.

  • seed – Random seed for reproducibility.

Yields:

A pseudo-random permutation of [0, n).

>>> list(feistel_permutation_generator(10))
[1, 8, 0, 5, 3, 6, 9, 7, 4, 2]
>>> list(feistel_permutation_generator(10, seed=42))
[5, 3, 1, 6, 4, 2, 8, 0, 9, 7]

Make sure all elements are visited:

>>> sorted(list(feistel_permutation_generator(100, seed=42))) == list(range(100))
True

We can have infinite permutations without blowing up memory:

>>> for i, perm in enumerate(feistel_permutation_generator(100**2000)):
...     if i > 4: break
...     print(f"Permutation {i}: {str(perm)[:20]}...")
Permutation 0: 56877730339930604433...
Permutation 1: 31140272880303506593...
Permutation 2: 89677538354424247341...
Permutation 3: 94477358131828883980...
Permutation 4: 37089694092416945146...
class FeistelHelpers[source]#

Bases: object

Helper functions for the Feistel permutation generator.

static round_prf(
seed: int,
round_no: int,
value: int,
out_bits: int,
) → int[source]#

Small deterministic Pseudo-Random Function (PRF) used inside the Feistel network.

Parameters:
  • seed – Seed for the PRF.

  • round_no – Round number (0-3).

  • value – Input value.

  • out_bits – Output bit-width.

Returns:

The PRF output.

static permute(
x: int,
seed: int,
bits: int,
rounds: int = 4,
) → int[source]#

Feistel permutation over a fixed bit-width domain.

Parameters:
  • x – Input value.

  • seed – Random seed for the permutation.

  • bits – Bit-width of the domain.

  • rounds – Number of rounds to apply (default: 4).

Returns:

Permuted value.

sorting#

sort_dict_keys(
dictionary: dict[T, Any],
order: list[T],
reverse: bool = False,
) → dict[T, Any][source]#

Sort dictionary keys using a given order list (reverse optional)

Parameters:
  • dictionary – The dictionary to sort

  • order – The order list

  • reverse – Whether to sort in reverse order (given to sorted function which behaves differently than order.reverse())

Returns:

The sorted dictionary

>>> sort_dict_keys({'b': 2, 'a': 1, 'c': 3}, order=["a", "b", "c"])
{'a': 1, 'b': 2, 'c': 3}
>>> sort_dict_keys({'b': 2, 'a': 1, 'c': 3}, order=["a", "b", "c"], reverse=True)
{'c': 3, 'b': 2, 'a': 1}
>>> sort_dict_keys({'b': 2, 'a': 1, 'c': 3, 'd': 4}, order=["c", "b"])
{'c': 3, 'b': 2, 'a': 1, 'd': 4}