π§° collections#
This module provides utilities for collection manipulation:
Registry- Dictionary that registers any object by decoratorunique_list()- Remove duplicates from a list while preserving order using object id, hash or strat_least_n()- Check if at least n elements in an iterable satisfy a given predicatesort_dict_keys()- Sort dictionary keys using a given order list (ascending or descending)affine_permutation_generator()- Generate a memory-efficient pseudo-random permutation of[0, n)feistel_permutation_generator()- Memory-efficient pseudo-random permutation of[0, n)from a Feistel networkupsert_in_dataframe()- Insert or update a row in a Polars DataFrame based on primary keys
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"]())
dataframe#
- upsert_in_dataframe(
- df: pl.DataFrame,
- new_entry: dict[str, Any],
- primary_keys: list[str] | dict[str, Any] | None = None,
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',
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,
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,
Bases:
dict[str,T],GenericDictionary 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,
Register any object by its own name or a custom name.
Python applies stacked decorators from bottom to top. Put
registeroutermost when the registry should keep the fully decorated object.
shuffle#
- affine_permutation_generator(
- n: int,
- seed: int = 0,
Generate a memory-efficient pseudo-random permutation of
[0, n).Each
iin[0, n)can only be visited once thanks to the affine bijection:(a*i + b) % nwhereaandbare random integers and coprime withn.- 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,
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:
objectHelper functions for the Feistel permutation generator.
- static round_prf(
- seed: int,
- round_no: int,
- value: int,
- out_bits: int,
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,
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( ) 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}