Skip to content

Utils

feu.utils

Contain the utility functions.

feu.utils.command

Contain utility functions to run commands.

feu.utils.command.run_command

run_command(argv: Sequence[str]) -> None

Execute a command given as an argument vector.

The command is not run in a shell and is not tokenised, so it behaves the same way on Linux, macOS and Windows. The command is logged before it runs.

Parameters:

Name Type Description Default
argv Sequence[str]

The command and its arguments, e.g. ["python", "-m", "pip", "--version"].

required

Raises:

Type Description
CalledProcessError

If the command exits with a non-zero status.

Example
>>> from feu.utils.command import run_command
>>> run_command(["ls", "-l"])  # doctest: +SKIP

feu.utils.http

Contain utility functions to manage HTTP requests.

feu.utils.http.fetch_data

fetch_data(
    url: str,
    *,
    timeout: float = 10.0,
    headers: Mapping[str, str] | None = None,
    params: Mapping[str, Any] | None = None,
    accept: str | None = None,
) -> dict[str, Any]

Retrieve the JSON data for a given URL.

This function performs an HTTP GET request and parses the response body as JSON. It configures a retry policy for transient errors (e.g., 429, 500, 502, 503, 504), handles network and timeout failures, validates the HTTP response, and returns the parsed JSON payload. Any unrecoverable error is raised as a RuntimeError with a clear message.

Parameters:

Name Type Description Default
url str

The URL.

required
timeout float

The number of seconds to wait for the server to send data before giving up.

10.0
headers Mapping[str, str] | None

Optional HTTP headers to send.

None
params Mapping[str, Any] | None

Optional query parameters.

None
accept str | None

Optional value of the Accept header. An Accept entry of headers takes precedence.

None

Returns:

Type Description
dict[str, Any]

The parsed JSON object returned.

Raises:

Type Description
RuntimeError

If the request times out, if a network or HTTP error occurs, or if the response body contains invalid JSON.

MissingPackageError

If requests is not installed.

Example
>>> from feu.utils.http import fetch_data
>>> data = fetch_data("https://pypi.org/pypi/requests/json")  # doctest: +SKIP

feu.utils.http.fetch_response

fetch_response(
    url: str,
    *,
    timeout: float = 10.0,
    headers: Mapping[str, str] | None = None,
    params: Mapping[str, Any] | None = None,
    accept: str | None = None,
) -> Response

Retrieve data from a given URL with automatic retry logic.

This function performs an HTTP GET request with a configured retry policy for transient errors (429, 500, 502, 503, 504), with exponential backoff and up to 5 retry attempts on https:// and http://. The request has a User-Agent: feu/<version> header. The function validates the HTTP response and raises detailed errors for failures. The session is closed before the function returns, so streaming is not supported.

Parameters:

Name Type Description Default
url str

The URL to fetch.

required
timeout float

The number of seconds to wait for the server to send data before giving up. Defaults to 10.0.

10.0
headers Mapping[str, str] | None

Optional HTTP headers to send.

None
params Mapping[str, Any] | None

Optional query parameters.

None
accept str | None

Optional value of the Accept header. An Accept entry of headers takes precedence.

None

Returns:

Type Description
Response

A requests.Response object containing the HTTP response.

Raises:

Type Description
RuntimeError

If the request times out, or if a network/HTTP error occurs.

MissingPackageError

If requests is not installed.

Example
>>> from feu.utils.http import fetch_response
>>> response = fetch_response("https://pypi.org/pypi/requests/json")  # doctest: +SKIP
>>> response.json()  # doctest: +SKIP

feu.utils.io

Contain utility functions to load and save data in JSON format.

feu.utils.io.generate_unique_tmp_path

generate_unique_tmp_path(path: Path) -> Path

Return a unique temporary path given a path.

This function adds a UUID to the file name, before the extensions, e.g. data.json becomes data-<uuid>.json.

Parameters:

Name Type Description Default
path Path

The input path.

required

Returns:

Type Description
Path

The unique path, in the same directory as path.

Example
>>> import tempfile
>>> from pathlib import Path
>>> from feu.utils.io import generate_unique_tmp_path
>>> with tempfile.TemporaryDirectory() as tmpdir:
...     path = generate_unique_tmp_path(Path(tmpdir).joinpath("data.json"))
...     path
...
PosixPath('/.../data-....json')

feu.utils.io.load_json

load_json(path: Path) -> Any

Load the data from a given JSON file.

Parameters:

Name Type Description Default
path Path

The path to the JSON file.

required

Returns:

Type Description
Any

The data from the JSON file.

Raises:

Type Description
FileNotFoundError

if the file does not exist.

JSONDecodeError

if the file does not contain valid JSON.

Example
>>> import tempfile
>>> from pathlib import Path
>>> from feu.utils.io import save_json, load_json
>>> with tempfile.TemporaryDirectory() as tmpdir:
...     path = Path(tmpdir).joinpath("data.json")
...     save_json({"key1": [1, 2, 3], "key2": "abc"}, path)
...     data = load_json(path)
...     data
...
{'key1': [1, 2, 3], 'key2': 'abc'}

feu.utils.io.save_json

save_json(
    to_save: Any, path: Path, *, exist_ok: bool = False
) -> None

Save the given data in a JSON file.

The parent directories are created if needed. The data is first written to a unique temporary file, which is then moved to path, so an interrupted write does not corrupt an existing file.

Parameters:

Name Type Description Default
to_save Any

The data to write in a JSON file. It must be serializable by json.dump.

required
path Path

The path where to write the JSON file.

required
exist_ok bool

If False (the default), FileExistsError is raised if the target file already exists. If True, the existing file is overwritten.

False

Raises:

Type Description
FileExistsError

if the file already exists and exist_ok=False.

IsADirectoryError

if path is a directory.

TypeError

if to_save is not JSON serializable.

Example
>>> import tempfile
>>> from pathlib import Path
>>> from feu.utils.io import load_json, save_json
>>> with tempfile.TemporaryDirectory() as tmpdir:
...     path = Path(tmpdir).joinpath("data.json")
...     save_json({"key1": [1, 2, 3], "key2": "abc"}, path)
...     data = load_json(path)
...     data
...
{'key1': [1, 2, 3], 'key2': 'abc'}

feu.utils.mapping

Contain utility functions for mappings.

feu.utils.mapping.sort_by_keys

sort_by_keys(mapping: Mapping[Any, Any]) -> dict[Any, Any]

Sort a dictionary by keys.

Parameters:

Name Type Description Default
mapping Mapping[Any, Any]

The dictionary to sort.

required

Returns:

Type Description
dict[Any, Any]

A new dictionary sorted by keys in ascending order.

Raises:

Type Description
TypeError

if the keys cannot be compared.

Example
>>> from feu.utils.mapping import sort_by_keys
>>> sort_by_keys({"dog": 1, "cat": 5, "fish": 2})
{'cat': 5, 'dog': 1, 'fish': 2}

feu.utils.mapping.sort_by_values

sort_by_values(
    mapping: Mapping[Any, Any],
) -> dict[Any, Any]

Sort a dictionary by values.

Parameters:

Name Type Description Default
mapping Mapping[Any, Any]

The dictionary to sort.

required

Returns:

Type Description
dict[Any, Any]

A new dictionary sorted by values in ascending order. The order of the items with equal values is preserved.

Raises:

Type Description
TypeError

if the values cannot be compared.

Example
>>> from feu.utils.mapping import sort_by_values
>>> sort_by_values({"dog": 1, "cat": 5, "fish": 2})
{'dog': 1, 'fish': 2, 'cat': 5}

feu.utils.package

Contain utility functions to manage packages.

feu.utils.package.PackageSpec dataclass

Define a dataclass to represent a package specification.

Parameters:

Name Type Description Default
name str

The package name.

required
version str | None

The package version request: an exact version ("2.4.0"), a wildcard ("2.4.*") or ""/None for the latest version. The string representation pins the version with == unless the request is the latest version. None is stored as "".

''
extras Sequence[str] | None

Optional package extra dependencies. A list is stored as a tuple.

()
Example
>>> from feu.utils.package import PackageSpec
>>> pkg1 = PackageSpec("my_package")
>>> pkg1
PackageSpec(name='my_package', version='', extras=())
>>> str(pkg1)
'my_package'
>>> pkg2 = PackageSpec("my_package", version="1.2.3")
>>> pkg2
PackageSpec(name='my_package', version='1.2.3', extras=())
>>> str(pkg2)
'my_package==1.2.3'
>>> pkg3 = PackageSpec("my_package", version="1.*", extras=["security", "socks"])
>>> pkg3
PackageSpec(name='my_package', version='1.*', extras=('security', 'socks'))
>>> str(pkg3)
'my_package[security,socks]==1.*'

feu.utils.package.PackageSpec.to_requirement

to_requirement() -> Requirement

Convert to a packaging.requirements.Requirement.

Returns:

Type Description
Requirement

The current package as a requirement.

Example
>>> from feu.utils.package import PackageSpec
>>> PackageSpec("my_package", version="1.2.*").to_requirement()
<Requirement('my_package==1.2.*')>

feu.utils.package.PackageSpec.with_version

with_version(version: str | None) -> PackageSpec

Create a new PackageSpec instance with the given version.

Parameters:

Name Type Description Default
version str | None

The new version request to apply.

required

Returns:

Type Description
PackageSpec

A new instance of PackageSpec with the updated version.

Example
>>> from feu.utils.package import PackageSpec
>>> pkg = PackageSpec("my_package", version="1.2.0")
>>> pkg
PackageSpec(name='my_package', version='1.2.0', extras=())
>>> pkg2 = pkg.with_version("1.2.3")
>>> pkg2
PackageSpec(name='my_package', version='1.2.3', extras=())

feu.utils.registry

Contain a generic registry to register and look up values by name.

feu.utils.registry.Registry

Bases: Generic[T]

Register values and look them up by key.

This is the only implementation of "register and look up by name" of feu: the installer registry and the dependency resolver registry are instances of it.

Parameters:

Name Type Description Default
kind str

What the registry holds, e.g. "installer". It is used in the error messages.

required
normalize Callable[[str], str] | None

A function applied to every key before it is stored or looked up, e.g. packaging.utils.canonicalize_name or str.lower. None means the key is used as is.

None
Example
>>> from feu.utils.registry import Registry
>>> registry = Registry[int]("number", normalize=str.lower)
>>> registry.register("One", 1)
>>> registry.find("ONE")
1
>>> "one" in registry
True
>>> registry.keys()
['one']

feu.utils.registry.Registry.find

find(key: str) -> T

Find the value registered for a key.

Parameters:

Name Type Description Default
key str

The key.

required

Returns:

Type Description
T

The registered value.

Raises:

Type Description
KeyError

If no value is registered for the key. The message lists the known keys.

Example
>>> from feu.utils.registry import Registry
>>> registry = Registry[int]("number")
>>> registry.register("one", 1)
>>> registry.find("one")
1

feu.utils.registry.Registry.get

get(key: str) -> T | None
get(key: str, default: D) -> T | D
get(
    key: str, default: D | None = None
) -> T | D | None

Get the value registered for a key, or a default.

Parameters:

Name Type Description Default
key str

The key.

required
default D | None

The value returned if no value is registered for the key.

None

Returns:

Type Description
T | D | None

The registered value, or default.

Example
>>> from feu.utils.registry import Registry
>>> registry = Registry[int]("number")
>>> registry.get("one", 0)
0

feu.utils.registry.Registry.keys

keys() -> list[str]

Get the registered keys.

Returns:

Type Description
list[str]

The normalized keys, sorted.

Example
>>> from feu.utils.registry import Registry
>>> registry = Registry[int]("number")
>>> registry.register_many({"two": 2, "one": 1})
>>> registry.keys()
['one', 'two']

feu.utils.registry.Registry.register

register(
    key: str, value: T, *, exist_ok: bool = False
) -> None

Register a value for a key.

Parameters:

Name Type Description Default
key str

The key, e.g. an installer name or a package name.

required
value T

The value to register.

required
exist_ok bool

If False, a RuntimeError is raised when a value is already registered for the key. Set to True to overwrite.

False

Raises:

Type Description
RuntimeError

If a value is already registered for the key and exist_ok is False.

Example
>>> from feu.utils.registry import Registry
>>> registry = Registry[int]("number")
>>> registry.register("one", 1)
>>> registry.register("one", 11, exist_ok=True)
>>> registry.find("one")
11

feu.utils.registry.Registry.register_many

register_many(
    mapping: Mapping[str, T], *, exist_ok: bool = False
) -> None

Register several values.

The values are registered one after the other, so the values before a conflict stay registered.

Parameters:

Name Type Description Default
mapping Mapping[str, T]

The mapping of key to value.

required
exist_ok bool

Forwarded to register.

False

Raises:

Type Description
RuntimeError

If a value is already registered for a key and exist_ok is False.

Example
>>> from feu.utils.registry import Registry
>>> registry = Registry[int]("number")
>>> registry.register_many({"one": 1, "two": 2})
>>> registry.keys()
['one', 'two']

feu.utils.platform

Contain platform utilities.

feu.utils.platform.get_current_arch

get_current_arch() -> str | None

Return the current CPU architecture using the registry's vocabulary.

The value returned by platform.machine() is mapped to one of "x86_64" or "arm64".

Returns:

Type Description
str | None

The architecture name, or None if it is not recognized.

Example
>>> from feu.utils.platform import get_current_arch
>>> get_current_arch()  # doctest: +SKIP
'x86_64'

feu.utils.platform.get_current_os

get_current_os() -> str | None

Return the current OS name using the registry's vocabulary.

The value returned by platform.system() is mapped to one of "linux", "macos", or "windows".

Returns:

Type Description
str | None

The OS name, or None if it is not recognized.

Example
>>> from feu.utils.platform import get_current_os
>>> get_current_os()  # doctest: +SKIP
'linux'

feu.utils.platform.get_python_version

get_python_version() -> str

Return the current Python version as a "major.minor" string.

Returns:

Type Description
str

The current Python version.

Example
>>> from feu.utils.platform import get_python_version
>>> get_python_version()  # doctest: +SKIP
'3.11'

feu.utils.platform.is_free_threaded

is_free_threaded() -> bool

Indicate whether the running Python interpreter is a free- threaded build with the GIL disabled.

Free-threaded builds (PEP 703 <https://peps.python.org/pep-0703/>_) expose sys._is_gil_enabled, which is only present starting from Python 3.13 free-threaded builds. On any other build, or when the GIL has been re-enabled at runtime, this returns False.

Returns:

Type Description
bool

True if the interpreter is running without the GIL, otherwise False.

Example
>>> from feu.utils.platform import is_free_threaded
>>> is_free_threaded()  # doctest: +SKIP
False