API reference#

Stouputils is a collection of utility modules designed to simplify and enhance the development process. It includes a range of tools for tasks such as execution of doctests, display utilities, decorators, as well as context managers.

Check the documentation for more details: https://stoupy51.github.io/stouputils/

⚙️ config#

Global configuration module for stouputils.

This module provides the StouputilsConfig class which contains global configuration options that control the behavior of various stouputils functions. Configuration values can be set programmatically or via environment variables.

Environment Variables:

Configuration options can be overridden using environment variables with the prefix STP_ or STOUPUTILS_ followed by the configuration variable name. STP_PROCESS_TITLE_PER_WORKER=false STOUPUTILS_PROCESS_TITLE_PER_WORKER=true

Usage:
from stouputils.config import StouputilsConfig as Cfg

# Change configuration programmatically
Cfg.PROCESS_TITLE_PER_WORKER = False
ENV_PARSERS: dict[str, Callable[[str], Any]] = {'bool': <function <lambda>>, 'float': <class 'float'>, 'int': <class 'int'>}[source]#

How an environment variable is read, by the type name of the option it overrides. Any other type keeps the string.

class StouputilsConfig[source]#

Bases: object

Global configuration class for stouputils.

VERBOSE_READING_ENV: bool = False[source]#

Configuration option for verbose output when reading environment variables when stouputils is imported.

  • If true, stouputils will print out the environment variables it reads and their values. Defaults to False.

RESET: str = '\x1b[0m'[source]#
BLACK: str = '\x1b[30m'[source]#
LIGHT_GRAY: str = '\x1b[37m'[source]#
GRAY: str = '\x1b[90m'[source]#
RED: str = '\x1b[91m'[source]#
GREEN: str = '\x1b[92m'[source]#
YELLOW: str = '\x1b[93m'[source]#
BLUE: str = '\x1b[94m'[source]#
MAGENTA: str = '\x1b[95m'[source]#
CYAN: str = '\x1b[96m'[source]#
WHITE: str = '\x1b[97m'[source]#
LINE_UP: str = '\x1b[1A'[source]#
BOLD: str = '\x1b[1m'[source]#

Terminal color/style constants used throughout the package.

Used by stouputils.print and the other modules printing colored text, such as stouputils.backup.

BAR_FORMAT: str = '{l_bar}{bar}\x1b[95m| {n_fmt}/{total_fmt} [{rate_fmt}{postfix}, {elapsed}<{remaining}]\x1b[0m'[source]#

Default bar format used for TQDM progress bars.

Used by: stouputils.print and stouputils.parallel for progress bars.

FORCE_RAISE_EXCEPTION: bool = False[source]#

If true, error_log parameter will be set to LogLevels.RAISE_EXCEPTION for every next handle_error calls, useful for stouputils.all_doctests to ensure exceptions are raised during testing instead of just logged.

CPU_COUNT: int = 4[source]#

Number of CPUs to use by default for parallel operations (int). Can be overridden by setting the OMP_NUM_THREADS or MKL_NUM_THREADS environment variables.

Used by: stouputils.parallel (modules common and multi) and other concurrency helpers.

MEMORY_MEGABYTES: float = 15983.046875[source]#

Memory this process may use, in MB, which is the container’s cap wherever it states one. 0.0 means neither the cap nor the host total could be read.

Used by: stouputils.mlflow (denominator of process/memory_usage_percentage).

PROCESS_TITLE_PER_WORKER: bool = True[source]#

Configuration option for process title in multiprocessing() function. - If true, process title is set only once per worker (reflecting worker index 0 to max_workers-1). - If false, process title is updated for each task (reflecting task index 0 to len(args)-1).

Defaults to True for easier/accurate worker identification.

Used by: stouputils.parallel.multi (see process_title_wrapper()).

CHUNK_SIZE: int = 1048576[source]#

Default chunk size for file I/O operations (bytes).

Used by: stouputils.backup and other modules performing chunked file operations.

LARGE_CHUNK_SIZE: int = 8388608[source]#

Larger chunk size for file I/O operations (bytes).

Used by: stouputils.backup and other modules needing larger I/O buffers.

COMMIT_TYPES: ClassVar[dict[str, str]] = {'api': 'API Changes', 'build': 'Build System', 'cd': 'Continuous Delivery', 'chore': 'Chores', 'ci': 'Continuous Integration', 'ci/cd': 'CI/CD', 'dep': 'Dependency Updates', 'deps': 'Dependency Updates', 'docs': 'Documentation', 'feat': 'Features', 'fix': 'Bug Fixes', 'hack': "Don't ask", 'init': 'Initial Commit', 'perf': 'Performance Improvements', 'refactor': 'Code Refactoring', 'release': 'Releases', 'revert': 'Reverts', 'security': 'Security', 'style': 'Style', 'test': 'Tests', 'uwu': 'UwU ༼ つ ◕_◕ ༽つ', 'wip': 'Work in Progress'}[source]#

Mapping of conventional commit short types to human-friendly headings used in changelogs.

Used by: stouputils.continuous_delivery.cd_utils (parsing and grouping conventional commits for changelogs).

AUTO_DOCS_REQUIREMENTS: tuple[str, ...] = ('myst_parser',)[source]#

List of requirements used by the automatic docs utilities.

Used by: stouputils.applications.automatic_docs (dependency checks for documentation generation).

SEGMENTS_UNIQUE_COLOR: tuple[float, float, float, float] = (1.0, 0.0, 0.0, 1.0)[source]#

Color add_default_colors_to_segments() gives the first segment unless skipped.

SEGMENTS_COLOR_CYCLE: tuple[tuple[float, float, float, float], ...] = ((0.0, 1.0, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (1.0, 1.0, 0.0, 1.0), (1.0, 0.0, 1.0, 1.0), (0.0, 1.0, 1.0, 1.0))[source]#

Colors add_default_colors_to_segments() cycles through for the other segments.

💤 lazy#

Marker that defers every import of a module under PEP 810.

Python 3.15 decides whether an import is lazy by evaluating name in __lazy_modules__, and the specification only requires that object to support __contains__. Answering yes to everything keeps the declaration down to one shared marker per module, instead of a list that has to be kept in step with every import statement. Older Python versions ignore __lazy_modules__ entirely.

Star imports, __future__ imports and imports inside a try block stay eager whatever this marker says, since PEP 810 refuses to defer those.

class AlwaysLazy[source]#

Bases: object

Container that reports every module name as deferrable.

ALWAYS_LAZY: AlwaysLazy = <stouputils.lazy.AlwaysLazy object>[source]#

Shared marker assigned to __lazy_modules__ at the top of every module in the package.

🖥️ system#

What this process is actually allowed to use, as opposed to what the host reports.

The kernel interfaces every tool reads describe the machine, not the container. A pod capped at 12 of the machine’s 192 cores therefore reports 6 % CPU while it is saturated, and a 96 GiB cap against 2.4 TiB of host RAM reads as 4 % while the pod is about to be killed. Cgroup v2 is where the real ceiling is stated.

Outside a capped container both fall back to the host, which is the right answer there. Cgroup v1 is not read, its interface having been superseded on every distribution still receiving updates.

CPU_COUNT and MEMORY_MEGABYTES are what the rest of the package reads these through.

import os
import psutil
import stouputils as stp

# What the machine has
stp.info("Host:", os.cpu_count(), "CPUs and", psutil.virtual_memory().total // 2**20, "MB")

# What this process may really use, less inside a container with limits
stp.info("Usable here:", stp.cpu_limit(), "CPUs and", round(stp.memory_limit_megabytes()), "MB")
Terminal output of the example, the host next to what the container allows
CPU_MAX_PATH: str = '/sys/fs/cgroup/cpu.max'[source]#

Cgroup v2 file holding "<quota> <period>" in microseconds, or "max <period>" when uncapped.

MEMORY_MAX_PATH: str = '/sys/fs/cgroup/memory.max'[source]#

Cgroup v2 file holding the memory cap in bytes, or "max" when uncapped.

MEMINFO_PATH: str = '/proc/meminfo'[source]#

Kernel file whose MemTotal line is the host fallback when no cgroup cap is set.

MEGABYTE: int = 1048576[source]#

Bytes in the mebibyte memory limits are reported in.

cpu_limit() → float[source]#

Cores this process may use, falling back to the host’s count outside a capped container.

Fractional on purpose: a pod may be given half a core, and rounding that up or down is wrong either way. This is the ceiling itself, not a worker count. StouputilsConfig.CPU_COUNT is the latter, and it stays overridable by the usual thread-count environment variables.

>>> cpu_limit() > 0
True
memory_limit_megabytes() → float[source]#

Mebibytes this process may use, falling back to the host’s total outside a capped container.

Returns 0.0 when neither is readable, which a caller reads as “unknown” rather than as “none left”.

>>> memory_limit_megabytes() >= 0
True
parse_cpu_max(raw: str) → float | None[source]#

Cores a cgroup v2 cpu.max line allows, None when it sets no quota.

Parameters:

raw – Content of CPU_MAX_PATH, empty when the file is absent.

>>> parse_cpu_max("1200000 100000")
12.0
>>> parse_cpu_max("50000 100000")
0.5
>>> parse_cpu_max("max 100000") is None
True
>>> parse_cpu_max("") is None
True
parse_memory_max(raw: str) → float | None[source]#

Mebibytes a cgroup v2 memory.max line allows, None when it sets no cap.

Parameters:

raw – Content of MEMORY_MAX_PATH, empty when the file is absent.

>>> parse_memory_max("103079215104")
98304.0
>>> parse_memory_max("max") is None
True
parse_meminfo_total(raw: str) → float[source]#

Mebibytes the MemTotal line of /proc/meminfo reports, 0.0 when there is none.

>>> parse_meminfo_total("MemTotal:       16302056 kB")
15919.9765625
>>> parse_meminfo_total("")
0.0
read_limit_file(path: str) → str[source]#

The file’s content, empty when it does not exist or cannot be read.

>>> read_limit_file("/nonexistent/cgroup/file")
''

🏷️ version_pkg#

This module provides utility functions for printing package version information in a structured format, including the main package and its dependencies.

Functions:

  • show_version(): Print the version of the main package and its dependencies.

import stouputils as stp

# Versions of stouputils and of every package it depends on
stp.show_version()
Terminal output of the example, every dependency with its version
class VersionPrinter(
main_package: str = 'stouputils',
primary_color: str = '\x1b[96m',
secondary_color: str = '\x1b[92m',
max_depth: int = 2,
fully_displayed: set[str] = <factory>,
)[source]#

Bases: object

Prints a package and its dependencies, either as a flat list or as a tree.

>>> VersionPrinter.dependency_name('msgspec[toml,yaml]>=0.20.0')
'msgspec'
>>> VersionPrinter.dependency_name('numpy; python_version >= "3.14"')
'numpy'
main_package: str = 'stouputils'[source]#

Package the report starts from.

primary_color: str = '\x1b[96m'[source]#

Color of the package names and the separators.

secondary_color: str = '\x1b[92m'[source]#

Color of the version numbers.

max_depth: int = 2[source]#

Depth of the dependency tree, 2 or less printing a flat list instead.

fully_displayed: set[str][source]#

Packages whose dependencies were already printed once, collapsed into one line on the next occurrence.

static version_of(package_name: str) → str[source]#

Installed version of a package, empty when it is not installed.

Parameters:

package_name – Name of the package

Returns:

“1.0.0”

Return type:

Version of the package, ex

static dependency_name(requirement: str) → str[source]#

Name of the package a requirement refers to, without its version, extras or markers.

Parameters:

requirement – Requirement as written in the metadata, ex: “msgspec[toml,yaml]>=0.20.0”

Returns:

“msgspec”

Return type:

Name of the required package, ex

classmethod dependencies_of(
package_name: str,
with_extras: bool = True,
) → list[str][source]#

Sorted names of the packages a package depends on, without duplicates.

Parameters:
  • package_name – Name of the package

  • with_extras – Whether the dependencies of the optional extras are included

Returns:

[“numpy”, “tqdm”]

Return type:

Names of the dependencies, ex

separators(length: int) → tuple[str, str][source]#

Build the two separator lines framing the main package.

Parameters:

length – Width of the separators, in characters

Returns:

Separator holding the Python version, and plain separator

property minimum_width: int[source]#

Width leaving at least five dashes on each side of the Python version.

package_line(
package_name: str,
version: str,
suffix: str = '',
) → str[source]#

Build the line describing one package.

Parameters:
  • package_name – Name of the package

  • version – Version of the package

  • suffix – Text written after the version, ex: the already shown marker

Returns:

“stouputils v1.0.0”

Return type:

Colored line, ex

already_shown_line(
package_names: list[str],
) → str[source]#

Build the line collapsing every dependency whose own tree was printed earlier.

Parameters:

package_names – Names of the packages already printed

Returns:

“Already shown ^: markdown, pygments”

Return type:

Colored line, ex

static indent_block(
lines: list[str],
is_last: bool,
) → list[str][source]#

Hang a subtree under its parent, the first line carrying the connector.

Parameters:
  • lines – Lines of the subtree, indented relative to its own root

  • is_last – Whether the subtree is the last child of its parent

Returns:

Lines indented relative to the parent

>>> VersionPrinter.indent_block(["numpy", "└── tqdm"], is_last=False)
['├── numpy', '│   └── tqdm']
>>> VersionPrinter.indent_block(["numpy", "└── tqdm"], is_last=True)
['└── numpy', '    └── tqdm']
render_tree(
package_name: str,
visited: frozenset[str] = frozenset({}),
depth: int = 0,
) → list[str][source]#

Render a package and its dependencies, indented relative to that package.

Dependencies whose own tree was printed earlier are collapsed into a single line at the end, since repeating their name, version and marker on one line each drowns the ones worth reading.

Parameters:
  • package_name – Name of the package to render

  • visited – Packages already rendered in this branch, to stop cycles

  • depth – Current depth, the main package being at 0

Returns:

Lines of the subtree, the package itself being the first one

print_tree(package_name: str) → None[source]#

Print a package and its dependencies as a tree, walking each branch once.

Parameters:

package_name – Name of the package to print

print_flat() → None[source]#

Print the main package and its direct dependencies as an aligned list.

show() → None[source]#

Print the whole report, as a tree or as a flat list depending on the requested depth.

show_version(
main_package: str = 'stouputils',
primary_color: str = '\x1b[96m',
secondary_color: str = '\x1b[92m',
max_depth: int = 2,
) → None[source]#

Print the version of the main package and its dependencies.

Used by the “stouputils –version” command.

Parameters:
  • main_package – Name of the main package to show version for

  • primary_color – Color to use for the primary package name (defaults to cyan)

  • secondary_color – Color to use for the secondary package names (defaults to green)

  • max_depth – Maximum depth for dependency tree (<= 2 for flat, >=3 for tree)

show_version_cli() → None[source]#

Handle the “stouputils –version” CLI command