pyiv

Guice-style dependency injection for Python.

pyiv provides type-based constructor injection, scopes, qualified keys, and built-in test doubles. Runtime has zero third-party dependencies. Python 3.8+.

Key Features:

  • Type-based constructor injection from annotations

  • Scopes (per-injector and process-wide singletons, plus custom Scope)

  • Qualified keys with tag sets (Named), nearest match (Matched), Annotated constructor injection, and Binder

  • Version-conditioned bindings (for_version / for_package_version / for_package_present / for_package_absent / for_python_version) over named version domains

  • Module install, private modules, child injectors, and config override

  • Map/Set/List multibinders; Stage.PRODUCTION eager singletons

  • Reflection to discover implementations in a package

  • Use-case stdlib doubles (files, time, console, log, process, http, …)

  • Zero runtime dependencies

Quick Start:

>>> from pyiv import Config, get_injector
>>> class Database:
...     pass
>>> class PostgreSQL(Database):
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         self.register(Database, PostgreSQL)
>>> injector = get_injector(MyConfig)
>>> isinstance(injector.inject(Database), PostgreSQL)
True

Multiple Implementations With Tags:

>>> from pyiv import Config, get_injector, Key, Named, Matched
>>> class Encoder:
...     def __init__(self, kind: str = ""):
...         self.kind = kind
>>> class JSONEncoder(Encoder):
...     def __init__(self):
...         super().__init__("json")
>>> class PrettyJSONEncoder(Encoder):
...     def __init__(self):
...         super().__init__("pretty")
>>> class EncoderConfig(Config):
...     def configure(self):
...         self.register_key(Key(Encoder, Named("json")), JSONEncoder)
...         self.register_key(
...             Key(Encoder, Named(["json", "pretty"], default=True)),
...             PrettyJSONEncoder,
...         )
>>> inj = get_injector(EncoderConfig)
>>> inj.inject(Key(Encoder, Matched(required=["json"], prefer=["pretty"]))).kind
'pretty'
>>> inj.inject(Encoder).kind
'pretty'

Constructor Annotated[T, Named|Matched] (Python 3.9+) is documented in the keys guide; use inject(Key(...)) when you need an explicit lookup.

Version-conditioned bindings:

>>> from pyiv import Config, get_injector
>>> from pyiv.version import FixedPythonVersionProvider, PythonVersionProvider
>>> class Runner:
...     kind = "base"
>>> class LegacyRunner(Runner):
...     kind = "legacy"
>>> class ModernRunner(Runner):
...     kind = "modern"
>>> class RunnerConfig(Config):
...     def configure(self):
...         b = self.get_binder()
...         b.bind(PythonVersionProvider).to_instance(
...             FixedPythonVersionProvider("3.10.0")
...         )
...         b.bind(Runner).to(LegacyRunner).for_python_version("<3.11")
...         b.bind(Runner).to(ModernRunner).for_python_version(">=3.11")
>>> get_injector(RunnerConfig).inject(Runner).kind
'legacy'

Package present / absent (optional accelerator):

>>> from pyiv import Config, get_injector
>>> from pyiv.version import MapVersionSource, package_version_domain
>>> class Encoder:
...     kind = "base"
>>> class FastEncoder(Encoder):
...     kind = "fast"
>>> class StdEncoder(Encoder):
...     kind = "std"
>>> domain = package_version_domain("cjson")
>>> class EncoderConfig(Config):
...     def configure(self):
...         b = self.get_binder()
...         b.version_source(domain, MapVersionSource({domain: "1.0.0"}))
...         b.bind(Encoder).to(FastEncoder).for_package_present("cjson")
...         b.bind(Encoder).to(StdEncoder).for_package_absent("cjson")
>>> get_injector(EncoderConfig).inject(Encoder).kind
'fast'
class pyiv.Argv[source]

Bases: ABC

Injectable program arguments and exit reporting.

Why this exists: CLI code that reads sys.argv or calls sys.exit is awkward in unit tests. Inject Argv instead.

Example

>>> from pyiv.process import MemoryArgv
>>> argv: Argv = MemoryArgv(["prog", "--verbose"])
>>> list(argv.args)
['prog', '--verbose']
abstract property args: Sequence[str]

Program arguments including argv[0].

abstract exit(code: int = 0) → None[source]

Request process exit with code.

class pyiv.AsyncHttpClient[source]

Bases: ABC

Async injectable HTTP client.

Why this exists: Async apps (inference adapters, SSE) need the same injectable contract as sync code without requiring httpx in core. Bind AsyncUrllibHttpClient or MemoryAsyncHttpClient.

Example

>>> import asyncio
>>> from pyiv.http import MemoryAsyncHttpClient
>>> async def _demo():
...     client = MemoryAsyncHttpClient()
...     client.add("GET", "http://example.test/", body=b"hi")
...     r = await client.get("http://example.test/")
...     return r.text
>>> asyncio.run(_demo())
'hi'
async aclose() → None[source]

Release transport resources (no-op by default).

async delete(url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, timeout: float | None = None) → HttpResponse[source]
async get(url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, timeout: float | None = None) → HttpResponse[source]
async patch(url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]
async post(url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]
async put(url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]
abstract async request(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]

Send an HTTP request and return a buffered response.

abstract stream(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → AbstractAsyncContextManager[AsyncStreamResponse][source]

Open an async streaming response (async context manager).

class pyiv.AsyncUrllibHttpClient(base_url=None, headers=None, timeout=None, https_only=False, sync_client=None, options=None)[source]

Bases: AsyncHttpClient

Async HTTP client that runs UrllibHttpClient in a thread pool.

Why this exists: Async apps can inject an HTTP client without httpx. Blocking urllib I/O runs via run_in_executor so the event loop stays free.

Example

>>> client = AsyncUrllibHttpClient()
>>> # Invalid schemes fail before any network I/O:
>>> import asyncio
>>> async def _bad():
...     await client.get("ftp://example.com/")
>>> asyncio.run(_bad())
Traceback (most recent call last):
    ...
ValueError: Only http:// and https:// URLs are allowed, got: ftp://example.com/
__init__(base_url=None, headers=None, timeout=None, https_only=False, sync_client=None, options=None) → None[source]
async aclose() → None[source]

Release transport resources (no-op by default).

async request(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]

Send an HTTP request and return a buffered response.

stream(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → AsyncIterator[AsyncStreamResponse][source]

Open an async streaming response (async context manager).

class pyiv.Base64SerDe[source]

Bases: SerDe

Base64 encoding SerDe.

Use this when binary payloads must travel as text (headers, logs, or text-only transports). Strings are UTF-8 encoded first; non-bytes objects fall back to pickle before encoding. Deserialize returns raw bytes.

Example

>>> from pyiv.serde.encodings import Base64SerDe
>>> serde = Base64SerDe()
>>> serde.handler_type
'base64'
>>> encoded = serde.serialize(b"hello")
>>> encoded
'aGVsbG8='
>>> serde.deserialize(encoded)
b'hello'
deserialize(data: str | bytes, target_type: Type[T] | None = None) → T[source]

Deserialize base64-encoded data.

Parameters:
  • data – The base64-encoded string or bytes

  • target_type – Optional type hint (returns bytes by default)

Returns:

Decoded bytes

property handler_type: str

Return the handler type identifier.

Returns:

The handler type identifier (“base64”)

serialize(obj: Any) → str[source]

Serialize using base64 encoding.

Parameters:

obj – The data to encode (bytes or string)

Returns:

Base64-encoded string

class pyiv.BaseConsole[source]

Bases: ABC

Abstract base class for console implementations.

Subclass this when you need a custom Console (file-like write plus optional TTY helpers). Implement write/flush/writable; terminal methods default to no-ops so simple sinks stay small. Prefer MemoryConsole for capturing print() in tests.

Why this exists: Shared base for Console implementations so TTY helpers default to no-ops.

Example

>>> from pyiv.console import BaseConsole
>>> class ListConsole(BaseConsole):
...     def __init__(self):
...         self.chunks = []
...     def write(self, s: str) -> int:
...         self.chunks.append(s)
...         return len(s)
...     def flush(self) -> None:
...         pass
...     def writable(self) -> bool:
...         return True
>>> c = ListConsole()
>>> print("hi", file=c)
>>> "".join(c.chunks)
'hi\n'
bold(enabled: bool = True) → None[source]

Enable or disable bold text (no-op by default).

clear() → None[source]

Clear the entire screen (no-op by default).

clear_line() → None[source]

Clear the current line (no-op by default).

clear_state() → None[source]

Clear all state (default: no-op).

clear_to_end_of_line() → None[source]

Clear from cursor to end of line (no-op by default).

abstract flush() → None[source]

Flush any buffered output.

get_color() → Tuple[int | None, int | None][source]

Get current color state (default: None, None).

get_cursor() → Tuple[int, int][source]

Get current cursor position (default: 0, 0).

get_cursor_position() → Tuple[int, int] | None[source]

Get current cursor position (default: None).

get_echo_enabled() → bool[source]

Get echo state (default: True).

get_events() → List[TerminalEvent][source]

Get event history (default: empty list).

get_raw_mode() → bool[source]

Get raw mode state (default: False).

get_screen() → List[List[str]][source]

Get screen buffer (default: empty).

get_screen_char(x: int, y: int) → str[source]

Get character at position from screen buffer (default: space).

Parameters:
  • x – Column (0-based)

  • y – Row (0-based)

Returns:

Character at position

get_screen_line(y: int) → str[source]

Get specific line from screen buffer (default: empty string).

Parameters:

y – Line number (0-based)

Returns:

Line contents as string

get_size() → Tuple[int, int][source]

Get terminal size (default: 80x24).

get_style() → Dict[str, bool][source]

Get text style state (default: all False).

Returns:

Dictionary of style flags

hide_cursor() → None[source]

Hide the cursor (no-op by default).

is_tty() → bool[source]

Check if output is a real terminal (default: False).

move_cursor(x: int, y: int) → None[source]

Move cursor to position (no-op by default).

move_cursor_down(n: int = 1) → None[source]

Move cursor down n lines (no-op by default).

move_cursor_home() → None[source]

Move cursor to home position (no-op by default).

move_cursor_left(n: int = 1) → None[source]

Move cursor left n columns (no-op by default).

move_cursor_right(n: int = 1) → None[source]

Move cursor right n columns (no-op by default).

move_cursor_up(n: int = 1) → None[source]

Move cursor up n lines (no-op by default).

read_char(timeout: float | None = None) → str | None[source]

Read a single character (default: None).

read_line(prompt: str = '') → str[source]

Read a line of input (default: empty string).

read_password(prompt: str = '') → str[source]

Read password with echo disabled (default: empty string).

reset_color() → None[source]

Reset colors to default (no-op by default).

restore_cursor() → None[source]

Restore saved cursor position (no-op by default).

save_cursor() → None[source]

Save current cursor position (no-op by default).

set_color(fg: int | None = None, bg: int | None = None) → None[source]

Set foreground and/or background color (no-op by default).

set_echo(enabled: bool) → None[source]

Turn echo on/off (no-op by default).

set_raw_mode(enabled: bool) → None[source]

Enable/disable raw mode (no-op by default).

show_cursor() → None[source]

Show the cursor (no-op by default).

underline(enabled: bool = True) → None[source]

Enable or disable underline (no-op by default).

abstract writable() → bool[source]

Check if console is writable.

Returns:

True if console supports writing

abstract write(s: str) → int[source]

Write string to console.

Parameters:

s – String to write

Returns:

Number of characters written

class pyiv.BaseFactory[source]

Bases: ABC, Generic[T]

ABC when you want a class-based factory with constructor injection.

Why this exists: Protocols are fine for typing; subclassing BaseFactory gives a real type the injector can construct, with dependencies supplied to __init__ and runtime args to create.

Example

>>> from pyiv.factory import BaseFactory
>>> class User:
...     def __init__(self, name: str):
...         self.name = name
>>> class UserFactory(BaseFactory[User]):
...     def create(self, name: str) -> User:
...         return User(name=name)
>>> UserFactory().create("Ada").name
'Ada'
abstract create(*args: Any, **kwargs: Any) → T[source]

Create an instance of type T.

Parameters:
  • *args – Positional arguments for instance creation

  • **kwargs – Keyword arguments for instance creation

Returns:

An instance of type T

class pyiv.BaseProvider[source]

Bases: ABC, Generic[T]

Abstract base class for provider implementations.

Why this exists: Subclassable provider when you need a real class the injector can construct.

Provides a concrete base class for providers that need to be instantiated. Subclasses should implement the get() method.

Example

>>> from pyiv.provider import BaseProvider, InstanceProvider
>>>
>>> class User:
...     def __init__(self, name: str):
...         self.name = name
>>>
>>> class UserProvider(BaseProvider[User]):
...     def get(self) -> User:
...         return User("alice")
>>>
>>> UserProvider().get().name
'alice'
>>> InstanceProvider(User("bob")).get().name
'bob'
abstract get() → T[source]

Get an instance of type T.

Returns:

An instance of type T

class pyiv.Binder(*args, **kwargs)[source]

Bases: Protocol

Fluent configuration API for contributing bindings to a Config.

Why this exists: Direct Config.register* calls work, but complex graphs read better as bind(X).to(Y).in_scope(Z). The binder also supports install, expose, version-conditioned bindings (including for_package_present / for_package_absent), and require_explicit_bindings.

Example

>>> from pyiv import Config, get_injector
>>> class Database:
...     pass
>>> class PostgreSQL(Database):
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         self.get_binder().bind(Database).to(PostgreSQL)
>>> isinstance(get_injector(MyConfig).inject(Database), PostgreSQL)
True

Version-conditioned bindings (env-stable selection at injector build):

>>> from pyiv import Config, get_injector
>>> from pyiv.version import FixedPythonVersionProvider, PythonVersionProvider
>>> class Runner:
...     kind = "base"
>>> class Legacy(Runner):
...     kind = "legacy"
>>> class Modern(Runner):
...     kind = "modern"
>>> class RunnerConfig(Config):
...     def configure(self):
...         b = self.get_binder()
...         b.bind(PythonVersionProvider).to_instance(
...             FixedPythonVersionProvider("3.12.0")
...         )
...         b.bind(Runner).to(Legacy).for_python_version("<3.11")
...         b.bind(Runner).to(Modern).for_python_version(">=3.11")
>>> get_injector(RunnerConfig).inject(Runner).kind
'modern'

Package present / absent (optional accelerator):

>>> from pyiv import Config, get_injector
>>> from pyiv.version import MapVersionSource, package_version_domain
>>> class Encoder:
...     kind = "base"
>>> class Fast(Encoder):
...     kind = "fast"
>>> class Std(Encoder):
...     kind = "std"
>>> domain = package_version_domain("cjson")
>>> class EncoderConfig(Config):
...     def configure(self):
...         b = self.get_binder()
...         b.version_source(domain, MapVersionSource({domain: "1.0"}))
...         b.bind(Encoder).to(Fast).for_package_present("cjson")
...         b.bind(Encoder).to(Std).for_package_absent("cjson")
>>> get_injector(EncoderConfig).inject(Encoder).kind
'fast'
__init__(*args, **kwargs)
bind(abstract: Type[T]) → BindingBuilder[T][source]

Start a binding configuration.

Parameters:

abstract – The abstract type to bind

Returns:

A binding builder for fluent configuration

bind_instance(abstract: Type[T], instance: T) → None[source]

Bind to a pre-created instance.

Parameters:
  • abstract – The abstract type

  • instance – The pre-created instance

bind_key(key: Key[T]) → BindingBuilder[T][source]

Start a binding configuration with a qualified key.

Register with Named (scalar or tag list/tuple). Matched is inject-only and rejected at registration. Duplicate Named tag sets for the same type raise; at most one Named(..., default=True) per type is allowed.

Parameters:

key – The qualified key to bind (Named, not Matched)

Returns:

A binding builder for fluent configuration

expose(type_or_key: Any) → None[source]

Expose a private binding to the parent environment.

Only meaningful on a PrivateConfig.

install(config: Any) → None[source]

Install another configuration module.

Parameters:

config – Another Config instance or subclass to install. Later installs overwrite the same type/key (last wins).

require_explicit_bindings() → None[source]

Require every injectable type to be bound explicitly (no JIT).

use_version_parser(domain: str, parser_name: str) → None[source]

Point domain at a named VersionParser.

version_parser(name: str, parser: Any) → None[source]

Register a named VersionParser.

version_source(domain: str, source: Any) → None[source]

Register a VersionSource for domain.

class pyiv.BindingBuilder(*args, **kwargs)[source]

Bases: Protocol, Generic[T]

Fluent steps after Binder.bind() (.to / .in_scope / .for_version / …).

Why this exists: A single register(...) call buries scope, provider, and version-condition choices in kwargs. The builder makes the binding shape readable as a chain while still writing the same Config store (or a version-candidate list).

Example

>>> from pyiv import Config, get_injector
>>> from pyiv.scope import SingletonScope
>>> class Database:
...     pass
>>> class PostgreSQL(Database):
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         self.get_binder().bind(Database).to(PostgreSQL).in_scope(SingletonScope())
>>> isinstance(get_injector(MyConfig).inject(Database), PostgreSQL)
True

Version condition (see pyiv.version for full examples):

>>> from pyiv import Config, get_injector
>>> from pyiv.version import FixedPythonVersionProvider, PythonVersionProvider
>>> class Api:
...     tag = "base"
>>> class V1(Api):
...     tag = "v1"
>>> class V2(Api):
...     tag = "v2"
>>> class ApiConfig(Config):
...     def configure(self):
...         b = self.get_binder()
...         b.bind(PythonVersionProvider).to_instance(
...             FixedPythonVersionProvider("3.12.0")
...         )
...         b.bind(Api).to(V1).for_python_version("<3.11")
...         b.bind(Api).to(V2).for_python_version(">=3.11")
>>> get_injector(ApiConfig).inject(Api).tag
'v2'

Package present / absent (optional accelerator):

>>> from pyiv import Config, get_injector
>>> class Encoder:
...     kind = "base"
>>> class Fast(Encoder):
...     kind = "fast"
>>> class Std(Encoder):
...     kind = "std"
>>> class MissingAccelConfig(Config):
...     def configure(self):
...         b = self.get_binder()
...         missing = "pyiv-definitely-not-installed-xyz"
...         b.bind(Encoder).to(Fast).for_package_present(missing)
...         b.bind(Encoder).to(Std).for_package_absent(missing)
>>> get_injector(MissingAccelConfig).inject(Encoder).kind
'std'
__init__(*args, **kwargs)
for_package_absent(distribution: str) → BindingBuilder[T][source]

Restrict this binding to when the distribution is not installed.

Sugar for for_package_version(distribution, "!"). Matches when importlib.metadata reports the distribution as missing. Pair with for_package_present() for an explicit both-sides choice, or use an unconditional fallback after for_package_present instead.

Example

>>> from pyiv import Config, get_injector
>>> class Encoder:
...     kind = "base"
>>> class FastEncoder(Encoder):
...     kind = "fast"
>>> class StdEncoder(Encoder):
...     kind = "std"
>>> class EncoderConfig(Config):
...     def configure(self):
...         b = self.get_binder()
...         b.bind(Encoder).to(FastEncoder).for_package_present(
...             "pyiv-definitely-not-installed-xyz"
...         )
...         b.bind(Encoder).to(StdEncoder).for_package_absent(
...             "pyiv-definitely-not-installed-xyz"
...         )
>>> get_injector(EncoderConfig).inject(Encoder).kind
'std'
Parameters:

distribution – Distribution name (importlib.metadata)

Returns:

Self for method chaining

for_package_present(distribution: str) → BindingBuilder[T][source]

Restrict this binding to when the distribution is installed.

Sugar for for_package_version(distribution, "*"). Matches any installed version; when the distribution is absent the candidate does not match — pair with for_package_absent() or an unconditional fallback registered after.

Pass the distribution name (as on PyPI / importlib.metadata), which may differ from the import package name.

Example

>>> from pyiv import Config, get_injector
>>> from pyiv.version import MapVersionSource, package_version_domain
>>> class Encoder:
...     kind = "base"
>>> class FastEncoder(Encoder):
...     kind = "fast"
>>> class StdEncoder(Encoder):
...     kind = "std"
>>> domain = package_version_domain("cjson")
>>> class EncoderConfig(Config):
...     def configure(self):
...         b = self.get_binder()
...         # Simulate an installed optional accelerator in tests.
...         b.version_source(domain, MapVersionSource({domain: "1.0.0"}))
...         b.bind(Encoder).to(FastEncoder).for_package_present("cjson")
...         b.bind(Encoder).to(StdEncoder).for_package_absent("cjson")
>>> get_injector(EncoderConfig).inject(Encoder).kind
'fast'
Parameters:

distribution – Distribution name (importlib.metadata)

Returns:

Self for method chaining

for_package_version(distribution: str, specifier: str) → BindingBuilder[T][source]

Restrict this binding to an installed distribution’s PEP 440 version.

Convenience for for_version with PackageVersionSource and the built-in "PEP440" Pep440VersionParser.

Pass PACKAGE_PRESENT ("*") / PACKAGE_ABSENT ("!") — or use for_package_present() / for_package_absent().

Example

>>> from pyiv import Config, get_injector
>>> from pyiv.version import MapVersionSource, package_version_domain
>>> class HttpClient:
...     name = "base"
>>> class Legacy(HttpClient):
...     name = "legacy"
>>> class Modern(HttpClient):
...     name = "modern"
>>> domain = package_version_domain("requests")
>>> class HttpConfig(Config):
...     def configure(self):
...         b = self.get_binder()
...         b.version_source(domain, MapVersionSource({domain: "2.31.0"}))
...         b.bind(HttpClient).to(Legacy).for_package_version(
...             "requests", "<2.30"
...         )
...         b.bind(HttpClient).to(Modern).for_package_version(
...             "requests", ">=2.30,<3"
...         )
>>> get_injector(HttpConfig).inject(HttpClient).name
'modern'
Parameters:
  • distribution – Distribution name (importlib.metadata), not necessarily the import package name

  • specifier – PEP 440 version specifier, or "*" / "!" for presence / absence

Returns:

Self for method chaining

for_python_version(specifier: str) → BindingBuilder[T][source]

Restrict this binding to the running interpreter’s PEP 440 version.

See the BindingBuilder class docstring for a runnable for_python_version example (with FixedPythonVersionProvider).

Parameters:

specifier – PEP 440 version specifier against sys.version_info

Returns:

Self for method chaining

for_version(domain: str, specifier: str, *, parser: Any = None) → BindingBuilder[T][source]

Restrict this binding to a named version domain + specifier.

Registers a version candidate instead of an unconditional binding. Prefer for_python_version(), for_package_version(), for_package_present(), or for_package_absent() when those cover the domain. See pyiv.version and the version-bindings guide.

Parameters:
Returns:

Self for method chaining

in_scope(scope: Scope) → BindingBuilder[T][source]

Set the scope for this binding.

Parameters:

scope – The scope to use

Returns:

Self for method chaining

to(implementation: Type[T]) → BindingBuilder[T][source]

Bind to a concrete implementation.

Parameters:

implementation – The concrete class to bind to

Returns:

Self for method chaining

to_instance(instance: T) → BindingBuilder[T][source]

Bind to a pre-created instance.

Parameters:

instance – The instance to bind to

Returns:

Self for method chaining

to_provider(provider: Provider[T]) → BindingBuilder[T][source]

Bind to a provider.

Parameters:

provider – The provider to use for instance creation

Returns:

Self for method chaining

class pyiv.CLICommand(args: Namespace, injector: Any | None = None)[source]

Bases: Command

Base class for one-shot CLI commands (not long-running services).

Use this for tools that init, run once, and exit. Override run() (and optionally init()/cleanup()); set self._exit_code for non-zero status. Do not override execute() — it owns KeyboardInterrupt / SystemExit handling.

Example

>>> import argparse
>>> from pyiv.command import CLICommand
>>> class EchoCommand(CLICommand):
...     @classmethod
...     def get_name(cls) -> str:
...         return "echo"
...     def run(self) -> None:
...         self._exit_code = 0
>>> EchoCommand(argparse.Namespace()).execute()
0
__init__(args: Namespace, injector: Any | None = None)[source]

Initialize CLI command with parsed arguments.

cleanup() → None[source]

Cleanup after CLI command (no-op by default, override if needed).

execute() → int[source]

Execute the CLI command lifecycle.

Returns:

Exit code (0 for success, non-zero for error)

init() → None[source]

Initialize CLI command (no-op by default, override if needed).

run() → None[source]

Run the CLI command (no-op by default).

Override this method to implement command logic. Set self._exit_code to return a non-zero status from execute().

class pyiv.ChainHandler[source]

Bases: ABC

Pluggable handler looked up by chain type and handler name/type.

Why this exists: Apps need interchangeable strategies (JSON vs pickle, HTTP vs HTTPS) without hard-coding classes at call sites. Register handlers on Config and resolve them with inject_chain_handler.

Example

>>> from pyiv.serde import JSONSerDe
>>> h: ChainHandler = JSONSerDe()
>>> h.chain_type is ChainType.ENCODING
True
>>> h.handler_type
'json'
abstract property chain_type: ChainType

Return the chain type this handler belongs to.

Returns:

The ChainType enum value

abstract handle(request: Any, **kwargs) → Any[source]

Handle a request.

Parameters:
  • request – The request to handle

  • **kwargs – Additional keyword arguments

Returns:

The result of handling the request

abstract property handler_type: str

Return the handler type identifier.

This identifies the specific implementation (e.g., “json”, “md5”, “quicksort”).

Returns:

A string identifying the handler type

class pyiv.ChainType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Category key for a family of chain-of-responsibility handlers.

Why this exists: SerDe and other pluggable handlers share the same registration/injection machinery but must not collide. ChainType namespaces those registries (encoding vs hashing, …).

Example

>>> from pyiv.chain import ChainType
>>> ChainType.ENCODING.value
'encoding'
>>> ChainType.HASHING.value
'hashing'
ENCODING = 'encoding'
HASHING = 'hashing'
SORTING = 'sorting'
class pyiv.Clock[source]

Bases: ABC

Abstract clock interface for time operations.

Why this exists: Call sites that use time.time()/sleep couple production to wall clock; inject Clock and bind SyntheticClock in tests.

This abstract class provides methods for time-related operations, allowing implementations to be swapped for testing or different time sources. Use RealClock for production code and SyntheticClock for testing.

Example

>>> from pyiv.clock import SyntheticClock
>>> clock = SyntheticClock(100.0)
>>> clock.time()
100.0
>>> clock.sleep(1.5)
>>> clock.time()
101.5
abstract monotonic() → float[source]

Get monotonic time (not affected by system clock adjustments).

Returns:

Monotonic time as float

abstract sleep(seconds: float) → None[source]

Sleep for specified duration.

Parameters:

seconds – Duration to sleep

abstract start_timer(interval: float, callback: Callable[[], None], repeat: bool = False) → Timer[source]

Start a timer that calls callback after interval.

Parameters:
  • interval – Time interval in seconds

  • callback – Function to call

  • repeat – If True, timer repeats

Returns:

Timer object

abstract thread_sleep(seconds: float) → None[source]

Sleep in current thread.

Parameters:

seconds – Duration to sleep

abstract time() → float[source]

Get current time as seconds since epoch.

Returns:

Current time as float

class pyiv.Command(args: Namespace, injector: Any | None = None)[source]

Bases: ABC

Base interface for discoverable CLI commands.

Use this when building hierarchical CLIs (command / subcommand trees) that should be discoverable via reflection and optionally receive a pyiv injector. Prefer CLICommand for one-shot tools and ServiceCommand for long-running processes.

Example

>>> import argparse
>>> from pyiv.command import Command
>>> class HelloCommand(Command):
...     @classmethod
...     def get_name(cls) -> str:
...         return "hello"
...     def execute(self) -> int:
...         return 0
>>> HelloCommand.get_name()
'hello'
>>> HelloCommand(argparse.Namespace()).execute()
0
__init__(args: Namespace, injector: Any | None = None)[source]

Initialize the command with parsed arguments.

Parameters:
  • args – Parsed command-line arguments

  • injector – Optional dependency injector for DI support

classmethod add_args(parser: ArgumentParser) → None[source]

Add arguments to the command’s argument parser.

Parameters:
  • cls – The class (implicit in classmethod)

  • parser – Argument parser to add arguments to

classmethod add_logging_args(parser: ArgumentParser) → None[source]

Add shared -v / -q / --log-level / --log-format flags.

Call from add_args when the command should configure pyiv.log. Apply options in init via configure_logging_from_args.

cleanup() → None[source]

Cleanup after command execution (optional lifecycle hook).

Override this method to: - Close database connections - Stop background tasks - Clean up any resources - Perform graceful shutdown

Called after execute() completes, even if an exception occurs.

configure_logging_from_args() → None[source]

Apply LogOptions from self.args using LogSetup.

Prefer injecting LogSetup from the injector when available; falls back to a process-local LogSetup instance.

abstract execute() → int[source]

Execute the command.

For long-running services, this typically calls: 1. init() - Initialize resources 2. run() - Main service loop 3. cleanup() - Clean up resources

For one-shot commands, implement the logic directly here.

Returns:

Exit code (0 for success, non-zero for error)

classmethod get_aliases() → List[str][source]

Get command aliases.

Parameters:

cls – The class (implicit in classmethod)

Returns:

List of alternative names for this command

classmethod get_description() → str[source]

Get the command description.

Parameters:

cls – The class (implicit in classmethod)

Returns:

Command description for help text

abstract classmethod get_name() → str[source]

Get the command name.

Parameters:

cls – The class (implicit in classmethod)

Returns:

Command name (e.g., “switchboard”, “start”, “create”)

classmethod get_subcommands() → List[Type[Command]][source]

Get subcommands of this command.

Parameters:

cls – The class (implicit in classmethod)

Returns:

List of command classes that are subcommands of this command

init() → None[source]

Initialize the command (optional lifecycle hook).

Override this method to: - Load configuration - Initialize resources (database connections, clients, etc.) - Set up signal handlers if needed - Perform any one-time setup

This is called automatically by execute() before run().

run() → None[source]

Run the command (optional lifecycle hook for long-running services).

Override this method for long-running services that need a main loop. For one-shot commands, override execute() directly instead.

This method should: - Start the main service loop - Block until service should stop - Handle the primary service functionality

This method should check self._shutdown_event periodically and exit gracefully when shutdown is requested.

setup_signal_handlers() → None[source]

Setup signal handlers for graceful shutdown.

Call this in init() for long-running services that need graceful shutdown.

class pyiv.CommandRunner(config: Any | None = None)[source]

Bases: object

Discovers and runs Command subclasses via reflection or import.

Use this as the entrypoint for a CLI package: discover commands under a package path, build an argparse tree, and execute the selected command with an optional pyiv injector from config.

Why this exists: Discover and dispatch hierarchical CLI commands with a shared lifecycle.

Example

>>> import argparse
>>> from pyiv.command import CLICommand, CommandRunner
>>> class GreetCommand(CLICommand):
...     @classmethod
...     def get_name(cls) -> str:
...         return "greet"
...     @classmethod
...     def get_description(cls) -> str:
...         return "Say hello"
...     def run(self) -> None:
...         self._exit_code = 0
>>> runner = CommandRunner()
>>> parser = runner.create_parser(
...     prog="demo", commands={"greet": GreetCommand}
... )
>>> args = parser.parse_args(["greet"])
>>> GreetCommand(args).execute()
0
__init__(config: Any | None = None)[source]

Initialize the command runner.

Parameters:

config – Optional pyiv Config instance for command discovery

create_parser(prog: str | None = None, description: str | None = None, commands: Dict[str, Type[Command]] | None = None) → ArgumentParser[source]

Create argument parser with discovered commands.

Parameters:
  • prog – Program name

  • description – Program description

  • commands – Optional pre-discovered commands dict

Returns:

Configured argument parser

discover_commands(package_path: str, pattern: str | None = None, recursive: bool = True) → Dict[str, Type[Command]][source]

Discover commands in a package using reflection.

Parameters:
  • package_path – Python package path (e.g., “agenticness.commands”)

  • pattern – Optional name pattern for filtering (e.g. *Command)

  • recursive – Whether to scan submodules recursively

Returns:

Dictionary mapping command names to command classes

run(package_path: str, prog: str | None = None, description: str | None = None, args: List[str] | None = None) → int[source]

Discover commands and run the appropriate one.

Parameters:
  • package_path – Python package path to discover commands in

  • prog – Program name

  • description – Program description

  • args – Optional command-line arguments (defaults to sys.argv[1:])

Returns:

Exit code from command execution

class pyiv.CompletedProcess(args: Sequence[str], returncode: int, stdout: str = '', stderr: str = '')[source]

Bases: object

Result of a process run (stdlib-shaped, frozen).

Why this exists: Boring DTO for assertions and Settings round-trip.

Example

>>> CompletedProcess(["true"], 0).returncode
0
__init__(args: Sequence[str], returncode: int, stdout: str = '', stderr: str = '') → None
args: Sequence[str]
returncode: int
stderr: str = ''
stdout: str = ''
class pyiv.Config[source]

Bases: object

Module of bindings that describe how to build an object graph.

Why this exists: Without a registration surface, every call site must know concrete classes. Subclass Config, override configure(), and register interfaces → implementations (or use get_binder()). For plugin catalogs, prefer contribute_map() / map_multibinder so hosts can extend membership with an explicit conflict policy.

Example

>>> from pyiv import Config, get_injector
>>> class Database:
...     pass
>>> class PostgreSQL(Database):
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         self.register(Database, PostgreSQL)
>>> isinstance(get_injector(MyConfig).inject(Database), PostgreSQL)
True
__init__()[source]

Initialize the configuration.

add_version_candidate(candidate: Any) → None[source]

Append a version-conditioned binding candidate.

Prefer the Binder for_version / for_package_version / for_package_present / for_package_absent / for_python_version helpers over calling this directly.

apply_version_selection() → None[source]

Resolve env-stable version candidates into ordinary bindings.

Called once at injector construction. For each abstract type with candidates:

Idempotent: a second call is a no-op.

configure()[source]

Override this method to register dependencies.

Example

def configure(self):

self.register(AbstractClass, ConcreteClass) self.register_instance(Logger, my_logger_instance)

contribute_map(value_type: Type[T], key: Any, implementation: Type[T], *, on_conflict: Literal['replace', 'error', 'keep'] = 'replace') → None[source]

Add a keyed implementation to a map multibind with conflict policy.

Prefer this over silent map_multibinder(...).add when hosts extend a library catalog and need an explicit rule for duplicate keys.

Parameters:
  • value_type – Catalog value type (map multibind bucket)

  • key – Catalog id (dict key)

  • implementation – Implementation class for the key

  • on_conflict – "replace" (default, same as bare add), "error" if the key already exists, or "keep" to leave the existing binding untouched

Example

>>> from pyiv import Config, get_injector
>>> class Handler:
...     pass
>>> class DefaultHandler(Handler):
...     pass
>>> class OverrideHandler(Handler):
...     pass
>>> class Lib(Config):
...     def configure(self):
...         self.contribute_map(Handler, "default", DefaultHandler)
>>> class StrictHost(Config):
...     def configure(self):
...         self.install(Lib)
...         self.contribute_map(
...             Handler, "extra", OverrideHandler, on_conflict="error"
...         )
>>> get_injector(StrictHost).catalog_keys(Handler)
['default', 'extra']
>>> class Clash(Config):
...     def configure(self):
...         self.install(Lib)
...         self.contribute_map(
...             Handler, "default", OverrideHandler, on_conflict="error"
...         )
>>> try:
...     Clash()
... except ValueError as exc:
...     "default" in str(exc)
True
contribute_map_entries(value_type: Type[T], mapping: Mapping[Any, Type[T]], *, on_conflict: Literal['replace', 'error', 'keep'] = 'replace') → None[source]

Contribute multiple map-multibind entries with the same conflict policy.

Example

>>> from pyiv import Config, get_injector
>>> class Tool:
...     pass
>>> class Grep(Tool):
...     pass
>>> class Lint(Tool):
...     pass
>>> class ToolsConfig(Config):
...     def configure(self):
...         self.contribute_map_entries(
...             Tool, {"grep": Grep, "lint": Lint}, on_conflict="error"
...         )
>>> get_injector(ToolsConfig).catalog_keys(Tool)
['grep', 'lint']
expose(type_or_key: Type | Key[Any]) → None[source]

Mark a binding as exposed from a private module.

On a regular Config this is a no-op store; PrivateConfig uses the set when installed into a parent.

get_binder() → Binder[source]

Get a binder for fluent configuration.

Returns:

A binder instance

get_chain_handler_instance(chain_type: ChainType, name: str) → ChainHandler | None[source]

Get a pre-registered chain handler instance.

Parameters:
  • chain_type – The chain type

  • name – The handler instance name

Returns:

The chain handler instance, or None if not found

get_chain_handler_registration(chain_type: ChainType, handler_type: str) → Type[ChainHandler] | None[source]

Get the registered chain handler class for a handler type.

Parameters:
  • chain_type – The chain type

  • handler_type – The handler type identifier

Returns:

The registered chain handler class, or None if not found

get_chain_handler_registration_by_name(chain_type: ChainType, name: str) → Tuple[Type[ChainHandler], str] | None[source]

Get the registered chain handler class and handler type for a name.

Parameters:
  • chain_type – The chain type

  • name – The handler instance name

Returns:

A tuple of (handler class, handler_type), or None if not found

get_chain_handler_singleton_type(chain_type: ChainType, name: str) → SingletonType[source]

Get the singleton type for a chain handler registration.

Parameters:
  • chain_type – The chain type

  • name – The handler instance name or handler type

Returns:

The singleton type, or SingletonType.NONE if not registered or not a singleton

get_exposed() → Set[Type | Key[Any]][source]

Return types/keys marked for exposure from a private module.

get_instance(abstract: Type) → Any | None[source]

Get a registered singleton instance for an abstract type.

Parameters:

abstract – The abstract class or interface

Returns:

The registered instance or None if not found

get_key_binding(key: Key[Any]) → Tuple[Type, Provider[Any] | None, Scope | None] | None[source]

Get a qualified binding for a key.

Parameters:

key – The qualified key

Returns:

Tuple of (type, provider, scope) or None if not found

get_map_multibinding(value_type: Type[T]) → Tuple[Dict[Any, Type], Dict[Any, Any]] | None[source]

Get map multibinding data for a value type.

Returns:

Tuple of (key->implementation, key->instance), or None if empty

get_multibinding(interface: Type[T]) → Tuple[Set[Type], List[Type], Set[Any], List[Any]] | None[source]

Get multibinding implementations for an interface.

Parameters:

interface – The interface type

Returns:

Tuple of (set_impls, list_impls, set_instances, list_instances) or None

get_named_bindings(binding_type: Type) → List[Tuple[Key[Any], Named, Tuple[Type, Provider[Any] | None, Scope | None]]][source]

Return all Named-qualified bindings for a type.

Used by Matched resolution and bare inject(Type) fallback.

Parameters:

binding_type – The type whose Named bindings to list

Returns:

List of (key, named_qualifier, binding_tuple) for each Named key

get_provider(abstract: Type) → Provider[Any] | None[source]

Get the provider for a registered type.

Parameters:

abstract – The abstract class or interface

Returns:

The provider, or None if not registered or no provider

get_registration(abstract: Type) → Type | Callable | None[source]

Get the registered concrete implementation for an abstract type.

Parameters:

abstract – The abstract class or interface

Returns:

The registered concrete class, callable, or None if not found

get_scope(abstract: Type) → Scope | None[source]

Get the scope for a registered type.

Parameters:

abstract – The abstract class or interface

Returns:

The scope, or None if not registered or no scope

get_singleton_type(abstract: Type) → SingletonType[source]

Get the singleton type for a registered abstract type.

Parameters:

abstract – The abstract class or interface

Returns:

The singleton type, or SingletonType.NONE if not registered or not a singleton

get_version_parser(name: str) → Any[source]

Return the VersionParser registered as name.

has_chain_handler_registration(chain_type: ChainType, handler_type: str) → bool[source]

Check if a chain handler is registered for a handler type.

Parameters:
  • chain_type – The chain type

  • handler_type – The handler type identifier

Returns:

True if registered, False otherwise

has_chain_handler_registration_by_name(chain_type: ChainType, name: str) → bool[source]

Check if a chain handler is registered by name.

Parameters:
  • chain_type – The chain type

  • name – The handler instance name

Returns:

True if registered, False otherwise

has_registration(abstract: Type) → bool[source]

Check if a registration exists for an abstract type.

Parameters:

abstract – The abstract class or interface

Returns:

True if registered, False otherwise

install(other: Type[Config] | Config) → None[source]

Install another config module into this one.

Regular configs are merged immediately. Unqualified type bindings last-wins. For identical Named tag sets, replace=True overwrites; two default=True Named bindings for the same type raise. PrivateConfig instances are queued and wired when the injector is created so exposed bindings can delegate into a child environment.

map_multibinder(value_type: Type[T]) → MapMultibinder[Any, T][source]

Create a map multibinder for keyed implementations of value_type.

merge_from(other: Config, *, replace: bool = True) → None[source]

Merge bindings from other into this config.

Parameters:
  • other – Source config

  • replace – If True, other overwrites existing keys; if False, existing bindings are kept.

multibinder(interface: Type[T], as_set: bool = True) → Multibinder[T][source]

Create a multibinder for multiple implementations.

Parameters:
  • interface – The interface type

  • as_set – If True, creates SetMultibinder, else ListMultibinder

Returns:

A multibinder instance

register(abstract: Type, concrete: Type | Callable, *, singleton: bool = False, singleton_type: SingletonType = SingletonType.NONE, scope: Scope | None = None, provider: Provider[Any] | None = None)[source]

Register a concrete implementation for an abstract type.

Parameters:
  • abstract – The abstract class or interface to register

  • concrete – The concrete class, instance, or factory function

  • singleton – If True, uses SINGLETON type (deprecated, use singleton_type or scope instead)

  • singleton_type – Type of singleton behavior (NONE, SINGLETON, or GLOBAL_SINGLETON)

  • scope – Scope for lifecycle management (takes precedence over singleton_type)

  • provider – Provider to use for instance creation (takes precedence over concrete)

Raises:
  • TypeError – If abstract is not a type

  • ValueError – If conflicting parameters are specified

register_chain_handler(chain_type: ChainType, handler_type: str, handler_class: Type[ChainHandler], *, singleton_type: SingletonType = SingletonType.SINGLETON)[source]

Register a chain handler implementation for a handler type.

This registers a default implementation for the handler type. When injecting by handler type (without a specific name), this implementation will be used.

Parameters:
  • chain_type – The chain type (e.g., ChainType.ENCODING, ChainType.HASHING)

  • handler_type – The handler type identifier (e.g., “json”, “md5”, “quicksort”)

  • handler_class – The chain handler implementation class

  • singleton_type – Type of singleton behavior (default: SINGLETON)

Raises:
  • TypeError – If handler_class is not a subclass of ChainHandler

  • ValueError – If handler_type is empty

register_chain_handler_by_name(chain_type: ChainType, name: str, handler_class: Type[ChainHandler], handler_type: str, *, singleton_type: SingletonType = SingletonType.SINGLETON)[source]

Register a named chain handler implementation.

This allows multiple implementations of the same handler type with different behaviors (e.g., “json-input”, “json-output”, “md5-fast”, “md5-secure”).

Parameters:
  • chain_type – The chain type (e.g., ChainType.ENCODING, ChainType.HASHING)

  • name – Unique name for this handler instance

  • handler_class – The chain handler implementation class

  • handler_type – The handler type identifier (e.g., “json”, “md5”)

  • singleton_type – Type of singleton behavior (default: SINGLETON)

Raises:
  • TypeError – If handler_class is not a subclass of ChainHandler

  • ValueError – If name or handler_type is empty

register_chain_handler_instance(chain_type: ChainType, name: str, instance: ChainHandler)[source]

Register a pre-created chain handler instance.

Parameters:
  • chain_type – The chain type

  • name – Unique name for this handler instance

  • instance – The pre-created chain handler instance

Raises:
register_instance(abstract: Type, instance: Any)[source]

Register a concrete instance for an abstract type.

Parameters:
  • abstract – The abstract class or interface

  • instance – The concrete instance to register

register_key(key: Key[Any], implementation: Type | Provider[Any], *, scope: Scope | None = None, replace: bool = False) → None[source]

Register a qualified binding using a Key.

Use Named (scalar or tag list/tuple) when binding. Matched is inject-only and rejected here.

For Named keys of the same type:

  • Duplicate tag sets raise ValueError unless replace=True (used by install / merge).

  • At most one Named(..., default=True) per type is allowed.

Parameters:
  • key – The qualified key (Named for multi-impl; not Matched)

  • implementation – The implementation class or provider

  • scope – Optional scope for lifecycle management

  • replace – If True, overwrite an existing identical Named tag set

Raises:
  • TypeError – If implementation is not a type or Provider, or key uses Matched

  • ValueError – On duplicate Named tag set (without replace) or a second default=True for the same type

register_map_multibinding(value_type: Type[T], key: Any, implementation: Type[T]) → None[source]

Register a keyed implementation in a map multibinding.

register_map_multibinding_instance(value_type: Type[T], key: Any, instance: T) → None[source]

Register a keyed instance in a map multibinding.

register_multibinding(interface: Type[T], implementation: Type[T], *, as_set: bool = True) → None[source]

Register an implementation in a multibinding.

Parameters:
  • interface – The interface type

  • implementation – The implementation class

  • as_set – If True, adds to set, else to list

register_multibinding_instance(interface: Type[T], instance: T, *, as_set: bool = True) → None[source]

Register a pre-created instance in a multibinding.

Parameters:
  • interface – The interface type

  • instance – The instance to add

  • as_set – If True, adds to set, else to list

register_provider(abstract: Type, provider: Provider[Any]) → None[source]

Register a provider for a type.

Parameters:
  • abstract – The abstract class or interface

  • provider – The provider to use for instance creation

register_version_parser(name: str, parser: Any) → None[source]

Register a named VersionParser.

"PEP440" is pre-registered. Custom grammars (OS releases, wire protocols) register under their own names and are selected with use_version_parser() or for_version(..., parser=...).

register_version_source(domain: str, source: Any) → None[source]

Register how to read the current version for domain.

Parameters:
  • domain – Named version domain (e.g. "python", "alpine")

  • source – A VersionSource

require_explicit_bindings() → None[source]

Disable just-in-time construction of unregistered concrete types.

requires_explicit_bindings() → bool[source]

Return whether explicit bindings are required.

resolve_version_parser(domain: str, parser_name: str | None = None) → Any[source]

Resolve the parser for a domain (candidate override → domain → PEP440).

singleton_bindings() → List[Type][source]

Return types that should be eagerly created in Stage.PRODUCTION.

use_version_parser(domain: str, parser_name: str) → None[source]

Point domain at a named VersionParser.

class pyiv.Console(*args, **kwargs)[source]

Bases: Protocol

Protocol for console output implementations.

Why this exists: print() to sys.stdout is hard to assert; inject Console and capture with MemoryConsole in tests.

Console provides a file-like interface for output, allowing print() statements to use dependency injection. This enables testing by capturing output without actually printing to stdout.

Console implementations should be file-like objects that support the standard file interface (write, flush, etc.) used by print().

Console also includes terminal functionality (TTY operations) for advanced features like spinners, animations, password prompts, and progress bars. Implementations that don’t support terminal features should provide no-op implementations that return safe defaults.

Example

>>> from pyiv.console import MemoryConsole
>>>
>>> console = MemoryConsole()
>>> print("Hello, World!", file=console)
>>> console.flush()
>>> "Hello, World!" in console.getvalue()
True
__init__(*args, **kwargs)
bold(enabled: bool = True) → None[source]

Enable or disable bold text.

clear() → None[source]

Clear the entire screen.

clear_line() → None[source]

Clear the current line.

clear_state() → None[source]

Clear all state (for test setup).

Resets terminal state including screen buffer, cursor position, colors, styles, and event history.

clear_to_end_of_line() → None[source]

Clear from cursor to end of line.

flush() → None[source]

Flush any buffered output.

Ensures all written data is actually output.

get_color() → Tuple[int | None, int | None][source]

Get current color state (for state inspection).

Returns:

Tuple of (fg, bg)

get_cursor() → Tuple[int, int][source]

Get current cursor position (for state inspection).

Returns:

Tuple of (x, y)

get_cursor_position() → Tuple[int, int] | None[source]

Get current cursor position.

Returns:

Tuple of (x, y) or None if not available

get_echo_enabled() → bool[source]

Get echo state (for state inspection).

Returns:

True if echo is enabled

get_events() → List[TerminalEvent][source]

Get event history (for state inspection).

Returns:

List of terminal events

get_raw_mode() → bool[source]

Get raw mode state (for state inspection).

Returns:

True if raw mode is enabled

get_screen() → List[List[str]][source]

Get screen buffer (for state inspection).

Returns:

2D list of screen contents

get_screen_char(x: int, y: int) → str[source]

Get character at position from screen buffer.

Parameters:
  • x – Column (0-based)

  • y – Row (0-based)

Returns:

Character at position

get_screen_line(y: int) → str[source]

Get specific line from screen buffer.

Parameters:

y – Line number (0-based)

Returns:

Line contents as string

get_size() → Tuple[int, int][source]

Get terminal size.

Returns:

Tuple of (columns, rows). Defaults to (80, 24) if not available.

get_style() → Dict[str, bool][source]

Get text style state (for state inspection).

Returns:

Dictionary of style flags (bold, underline, etc.)

hide_cursor() → None[source]

Hide the cursor.

is_tty() → bool[source]

Check if output is a real terminal.

Returns:

True if output is connected to a TTY, False otherwise

move_cursor(x: int, y: int) → None[source]

Move cursor to position.

Parameters:
  • x – Column (0-based)

  • y – Row (0-based)

move_cursor_down(n: int = 1) → None[source]

Move cursor down n lines.

move_cursor_home() → None[source]

Move cursor to home position (0, 0).

move_cursor_left(n: int = 1) → None[source]

Move cursor left n columns.

move_cursor_right(n: int = 1) → None[source]

Move cursor right n columns.

move_cursor_up(n: int = 1) → None[source]

Move cursor up n lines.

read_char(timeout: float | None = None) → str | None[source]

Read a single character (requires raw mode).

Parameters:

timeout – Optional timeout in seconds

Returns:

Character string or None if no input available

read_line(prompt: str = '') → str[source]

Read a line of input.

Parameters:

prompt – Optional prompt string to display

Returns:

Line of text (without newline)

read_password(prompt: str = '') → str[source]

Read password with echo disabled.

Parameters:

prompt – Prompt string to display

Returns:

Password string

reset_color() → None[source]

Reset colors to default.

restore_cursor() → None[source]

Restore saved cursor position.

save_cursor() → None[source]

Save current cursor position.

set_color(fg: int | None = None, bg: int | None = None) → None[source]

Set foreground and/or background color.

Parameters:
  • fg – Foreground color code (30-37 for basic, 30-37,90-97 for bright)

  • bg – Background color code (40-47 for basic, 100-107 for bright)

set_echo(enabled: bool) → None[source]

Turn echo on/off for password prompts.

Parameters:

enabled – True to enable echo, False to disable

set_raw_mode(enabled: bool) → None[source]

Enable/disable raw mode for character-by-character input.

Parameters:

enabled – True for raw mode, False for cooked mode

show_cursor() → None[source]

Show the cursor.

underline(enabled: bool = True) → None[source]

Enable or disable underline.

writable() → bool[source]

Check if console is writable.

Returns:

True if console supports writing

write(s: str) → int[source]

Write string to console.

Parameters:

s – String to write

Returns:

Number of characters written

exception pyiv.CreationError(message: str, *, path: Sequence[str] | None = None, causes: Sequence[BaseException] | None = None, ambiguous: bool = False)[source]

Bases: Exception

Raised when the injector cannot create or resolve a dependency.

Why this exists: Deep graphs fail far from the call site. This error carries the resolution path and optional nested causes so you can see App -> Service -> Database instead of a bare ValueError.

Parameters:
  • message – Human-readable failure reason

  • path – Resolution path from the root request to the failing type

  • causes – Nested failures (e.g. eager singleton warmup aggregation)

  • ambiguous – If True, multiple Named bindings matched and none was unique; Optional[T] must not treat this as a missing binding

Example

>>> err = CreationError("No binding", path=["Service", "Database"])
>>> "Service -> Database" in str(err)
True
__init__(message: str, *, path: Sequence[str] | None = None, causes: Sequence[BaseException] | None = None, ambiguous: bool = False)[source]
class pyiv.DateTimeService[source]

Bases: ABC

Abstract interface for UTC datetime operations.

Depend on this instead of calling datetime.now directly so production code can use PythonDateTimeService while tests inject MockDateTimeService with a fixed clock.

Example

>>> from datetime import datetime, timezone
>>> from pyiv.datetime_service import DateTimeService, MockDateTimeService
>>> def stamp(svc: DateTimeService) -> str:
...     return svc.now_utc_iso()
>>> fixed = datetime(2024, 1, 15, 10, 30, 0, tzinfo=timezone.utc)
>>> stamp(MockDateTimeService(fixed))
'2024-01-15T10:30:00+00:00'
abstract now_utc() → datetime[source]

Get current UTC datetime.

Returns:

Current datetime in UTC timezone

abstract now_utc_iso() → str[source]

Get current UTC datetime as ISO format string.

Returns:

30:00.123456+00:00”)

Return type:

Current datetime in UTC as ISO format string (e.g., “2024-01-15T10

class pyiv.Entropy[source]

Bases: ABC

Injectable source of randomness.

Why this exists: secrets / random at call sites make tests flaky. Inject Entropy and bind SyntheticEntropy with a seed.

Example

>>> from pyiv.entropy import SyntheticEntropy
>>> e: Entropy = SyntheticEntropy(seed=1)
>>> len(e.randbytes(4))
4
abstract choice(seq: Sequence[T]) → T[source]

Choose one element from seq.

abstract randbytes(n: int) → bytes[source]

Return n random bytes.

abstract token_urlsafe(nbytes: int = 32) → str[source]

Return a URL-safe token.

class pyiv.Environment[source]

Bases: ABC

Injectable view of process environment variables.

Why this exists: Mutating os.environ in tests leaks across cases. Depend on Environment and bind MemoryEnvironment in tests.

Example

>>> from pyiv.process import MemoryEnvironment
>>> env: Environment = MemoryEnvironment({"A": "1"})
>>> env.get("A")
'1'
abstract as_dict() → Dict[str, str][source]

Return a snapshot mapping.

abstract get(key: str, default: str | None = None) → str | None[source]

Return the value for key, or default.

abstract set(key: str, value: str) → None[source]

Set key to value.

abstract unset(key: str) → None[source]

Remove key if present.

class pyiv.ExitStatus(code: int = 0)[source]

Bases: object

Recorded process exit code.

Why this exists: Capture sys.exit intent without terminating tests.

Example

>>> ExitStatus(2).code
2
__init__(code: int = 0) → None
code: int = 0
class pyiv.Factory(*args, **kwargs)[source]

Bases: Protocol, Generic[T]

Callable creation API for objects that need runtime arguments.

Why this exists: A DI Provider builds one graph-managed instance. A Factory creates many instances with caller-supplied args (user id, connection string) while still allowing the factory itself to be injected.

Example

>>> from pyiv.factory import SimpleFactory
>>> class User:
...     def __init__(self, name: str):
...         self.name = name
>>> factory: Factory[User] = SimpleFactory(User)
>>> factory.create(name="Ada").name
'Ada'
__init__(*args, **kwargs)
create(*args: Any, **kwargs: Any) → T[source]

Create an instance of type T.

Parameters:
  • *args – Positional arguments for instance creation

  • **kwargs – Keyword arguments for instance creation

Returns:

An instance of type T

class pyiv.FactoryProvider(factory: Callable[[...], T])[source]

Bases: Generic[T]

Provider that wraps a factory function.

Why this exists: Adapt a zero-arg factory callable into the Provider protocol.

This provider calls a factory function each time get() is called. Useful for creating new instances on demand.

Example

>>> from pyiv.provider import FactoryProvider
>>>
>>> class User:
...     def __init__(self, name: str = "default"):
...         self.name = name
>>>
>>> def create_user() -> User:
...     return User(name="default")
>>>
>>> user_provider = FactoryProvider(create_user)
>>> user = user_provider.get()  # Calls create_user()
>>> user.name
'default'
>>> # Each call creates a new instance
>>> user2 = user_provider.get()
>>> user is not user2
True
__init__(factory: Callable[[...], T])[source]

Initialize provider with a factory function.

Parameters:

factory – A callable that creates instances of type T

get() → T[source]

Get an instance by calling the factory function.

Returns:

An instance created by the factory function

class pyiv.FileConsole(file: str | Path, mode: str = 'w', encoding: str = 'utf-8')[source]

Bases: BaseConsole

File-based console for testing.

Why this exists: When a test must verify output landed in a real file path.

This console writes output to a file, useful for testing scenarios where you want to verify output was written to a specific file.

Example

>>> import os
>>> import tempfile
>>> from pathlib import Path
>>> from pyiv.console import FileConsole
>>>
>>> fd, path = tempfile.mkstemp(suffix=".txt")
>>> os.close(fd)
>>> os.unlink(path)
>>> console = FileConsole(path)
>>> print("Test message", file=console)
>>> console.flush()
>>> "Test message" in Path(path).read_text()
True
>>> os.unlink(path)
__init__(file: str | Path, mode: str = 'w', encoding: str = 'utf-8')[source]

Initialize file-based console.

Parameters:
  • file – File path to write to

  • mode – File mode (default: “w” for write)

  • encoding – Text encoding (default: “utf-8”)

close() → None[source]

Close the file stream.

flush() → None[source]

Flush file buffer.

writable() → bool[source]

Check if file is writable.

Returns:

True if file mode supports writing

write(s: str) → int[source]

Write string to file.

Parameters:

s – String to write

Returns:

Number of characters written

class pyiv.Filesystem[source]

Bases: ABC

Abstract filesystem for injectable file I/O.

Why this exists: Production code that calls open() / pathlib directly is hard to unit-test without touching disk or mocking builtins. Depend on Filesystem and bind RealFilesystem in production and MemoryFilesystem in tests.

Example

>>> from pyiv.filesystem import MemoryFilesystem
>>> fs: Filesystem = MemoryFilesystem()
>>> fs.write_text("notes.txt", "hello")
>>> fs.read_text("notes.txt")
'hello'
abstract copy(src: str | Path, dst: str | Path) → None[source]

Copy a file.

Parameters:
  • src – Source path

  • dst – Destination path

abstract exists(path: str | Path) → bool[source]

Check if a path exists.

Parameters:

path – Path to check

Returns:

True if path exists, False otherwise

abstract get_size(path: str | Path) → int[source]

Get file size in bytes.

Parameters:

path – File path

Returns:

File size in bytes

abstract glob(pattern: str | Path) → Iterator[Path][source]

Glob pattern matching.

Parameters:

pattern – Glob pattern

Yields:

Matching paths

abstract is_dir(path: str | Path) → bool[source]

Check if path is a directory.

Parameters:

path – Path to check

Returns:

True if path is a directory, False otherwise

abstract is_file(path: str | Path) → bool[source]

Check if path is a file.

Parameters:

path – Path to check

Returns:

True if path is a file, False otherwise

abstract listdir(path: str | Path) → Iterator[str][source]

List directory contents.

Parameters:

path – Directory path

Yields:

Directory entry names

abstract mkdir(path: str | Path, parents: bool = False, exist_ok: bool = False) → None[source]

Create a directory.

Parameters:
  • path – Directory path

  • parents – Create parent directories if needed

  • exist_ok – Don’t raise error if directory exists

abstract move(src: str | Path, dst: str | Path) → None[source]

Move/rename a file or directory.

Parameters:
  • src – Source path

  • dst – Destination path

abstract open(file: str | Path, mode: str = 'r', encoding: str | None = None) → TextIO | BinaryIO[source]

Open a file.

Parameters:
  • file – File path

  • mode – File mode (r, w, a, rb, wb, etc.)

  • encoding – Text encoding (for text modes)

Returns:

File handle

abstract read_bytes(path: str | Path) → bytes[source]

Read bytes from a file.

Parameters:

path – File path

Returns:

File contents as bytes

abstract read_text(path: str | Path, encoding: str = 'utf-8') → str[source]

Read text from a file.

Parameters:
  • path – File path

  • encoding – Text encoding

Returns:

File contents as string

abstract rmdir(path: str | Path) → None[source]

Remove a directory.

Parameters:

path – Directory path

Remove a file.

Parameters:
  • path – File path

  • missing_ok – Don’t raise error if file doesn’t exist

walk(path: str | Path) → Iterator[tuple][source]

Walk directories yielding (dirpath, dirnames, filenames).

Default implementation uses listdir / is_dir / is_file.

abstract write_bytes(path: str | Path, content: bytes) → None[source]

Write bytes to a file.

Parameters:
  • path – File path

  • content – Bytes content to write

abstract write_text(path: str | Path, content: str, encoding: str = 'utf-8') → None[source]

Write text to a file.

Parameters:
  • path – File path

  • content – Text content to write

  • encoding – Text encoding

class pyiv.FixedPythonVersionProvider(version: str)[source]

Bases: PythonVersionProvider

Test double that returns a fixed interpreter version string.

Why this exists: Exercise version-conditioned bindings under many Python versions without changing the real runtime. Bind with binder.bind(PythonVersionProvider).to_instance(...).

Example

>>> from pyiv.version import FixedPythonVersionProvider
>>> FixedPythonVersionProvider("3.8.18").get_version()
'3.8.18'
__init__(version: str) → None[source]
Parameters:

version – PEP 440 version string to report (e.g. 3.10.12).

get_version() → str[source]

Return the fixed version passed to the constructor.

class pyiv.GlobalSingletonRegistry[source]

Bases: object

Process-wide store for GLOBAL_SINGLETON instances.

Why this exists: Some resources must be unique across injectors (shared caches). Tests call clear() between cases so state does not leak.

Example

>>> class Cache:
...     pass
>>> GlobalSingletonRegistry.clear()
>>> GlobalSingletonRegistry.set(Cache, Cache())
>>> GlobalSingletonRegistry.has(Cache)
True
>>> GlobalSingletonRegistry.clear()
classmethod clear() → None[source]

Clear all global singletons (useful for testing).

Parameters:

cls – The class (implicit in classmethod)

classmethod get(key: Type | str) → Any[source]

Get a global singleton instance.

Parameters:
  • cls – The class (implicit in classmethod)

  • key – The abstract type or string key to retrieve

Returns:

The singleton instance or None if not registered

classmethod has(key: Type | str) → bool[source]

Check if a global singleton exists.

Parameters:
  • cls – The class (implicit in classmethod)

  • key – The abstract type or string key to check

Returns:

True if a singleton exists, False otherwise

classmethod set(key: Type | str, instance: Any) → None[source]

Set a global singleton instance.

Parameters:
  • cls – The class (implicit in classmethod)

  • key – The abstract type or string key

  • instance – The instance to store

class pyiv.GlobalSingletonScope[source]

Bases: object

Global singleton scope (thread-safe).

Why this exists: One instance shared by all injectors in the process (thread-safe).

This scope caches instances globally across all injectors. The same instance is shared by all injectors and all threads. Access is thread-safe.

This is useful for truly global singletons like configuration, caches, or shared resources.

Example

>>> from pyiv.scope import GlobalSingletonScope
>>> from pyiv import Config
>>>
>>> class MyConfig(Config):
...     def configure(self):
...         # Global singleton (shared across all injectors)
...         self.register(Cache, RedisCache, scope=GlobalSingletonScope())
classmethod clear() → None[source]

Clear all global singleton instances (useful for testing).

Parameters:

cls – The class (implicit in classmethod)

classmethod has(key: Type | str | tuple) → bool[source]

Check if a global singleton exists.

Parameters:
  • cls – The class (implicit in classmethod)

  • key – The key to check

Returns:

True if a singleton exists, False otherwise

scope(key: Type | str | tuple, provider: Provider[Any]) → Provider[Any][source]

Scope provider to global singleton.

Parameters:
  • key – The key identifying the dependency

  • provider – The provider to scope

Returns:

A provider that returns the same global instance (thread-safe)

class pyiv.Hasher[source]

Bases: ABC

Injectable digest / HMAC helper.

Why this exists: Call sites that hard-code hashlib are harder to stub for fixed digests in tests.

Example

>>> from pyiv.hashing import RealHasher
>>> h: Hasher = RealHasher()
>>> h.digest("sha256", b"abc").hex()[:8]
'ba7816bf'
abstract digest(algorithm: str, data: bytes) → bytes[source]

Return a digest of data using algorithm.

abstract hmac_digest(algorithm: str, key: bytes, data: bytes) → bytes[source]

Return HMAC of data with key.

class pyiv.HttpClient[source]

Bases: ABC

Sync injectable HTTP client.

Why this exists: Apps should depend on a typed client (JSON bodies, status handling, optional streaming) instead of hard-coding urllib or a third-party stack. Bind UrllibHttpClient in production and MemoryHttpClient in tests.

Example

>>> from pyiv.http import HttpResponse, MemoryHttpClient
>>> client: HttpClient = MemoryHttpClient()
>>> client.add("GET", "http://example.test/x", body=b"ok")
>>> client.get("http://example.test/x").text
'ok'
close() → None[source]

Release transport resources (no-op by default).

delete(url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, timeout: float | None = None) → HttpResponse[source]

HTTP DELETE. See request.

get(url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, timeout: float | None = None) → HttpResponse[source]

HTTP GET. See request.

patch(url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]

HTTP PATCH. See request.

post(url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]

HTTP POST. See request.

put(url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]

HTTP PUT. See request.

abstract request(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]

Send an HTTP request and return a buffered response.

abstract stream(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → AbstractContextManager[StreamResponse][source]

Open a streaming response (context manager).

exception pyiv.HttpError[source]

Bases: Exception

Base error for injectable HTTP clients.

Why this exists: Call sites should catch one hierarchy whether the transport is urllib, requests, or a test double — not library-specific exception types.

Example

>>> from pyiv.http.errors import HttpError, HttpTimeoutError
>>> isinstance(HttpTimeoutError("late"), HttpError)
True
class pyiv.HttpResponse(status_code: int, headers: Mapping[str, str], content: bytes, url: str)[source]

Bases: object

Buffered HTTP response (status, headers, body).

Why this exists: Injectable clients need a typed response object with json() / text / raise_for_status() — not a bare dict — so streaming and status handling stay natural at call sites.

Example

>>> from pyiv.http.response import HttpResponse
>>> r = HttpResponse(200, {"Content-Type": "application/json"}, b'{"a": 1}', "http://x/")
>>> r.json()
{'a': 1}
>>> r.raise_for_status()
__init__(status_code: int, headers: Mapping[str, str], content: bytes, url: str) → None[source]
property content: bytes

Raw response body.

property headers: Dict[str, str]

Response headers (single-valued map).

json() → Any[source]

Parse the body as JSON.

Returns:

The decoded JSON value

Raises:

json.JSONDecodeError – If the body is not valid JSON

raise_for_status() → None[source]

Raise HttpStatusError if status_code is 4xx or 5xx.

property status_code: int

HTTP status code.

property text: str

Response body decoded as UTF-8 (replacement on errors).

property url: str

Final request URL (after redirects when the transport reports it).

exception pyiv.HttpStatusError(message: str, *, status_code: int, response: HttpResponse)[source]

Bases: HttpError

The response status indicated failure (raise_for_status).

Why this exists: Callers need the status code and response body after a failed request without re-parsing opaque exception strings.

Example

>>> from pyiv.http.errors import HttpStatusError
>>> from pyiv.http.response import HttpResponse
>>> resp = HttpResponse(404, {}, b"missing", "http://x/y")
>>> err = HttpStatusError("not found", status_code=404, response=resp)
>>> err.status_code
404
>>> err.response.content
b'missing'
__init__(message: str, *, status_code: int, response: HttpResponse) → None[source]
exception pyiv.HttpTimeoutError[source]

Bases: HttpError

The request exceeded its timeout.

Why this exists: Judge / inference callers often map timeouts to a distinct domain error (unavailable vs malformed response).

Example

>>> from pyiv.http.errors import HttpTimeoutError
>>> raise HttpTimeoutError("timed out")
Traceback (most recent call last):
    ...
pyiv.http.errors.HttpTimeoutError: timed out
class pyiv.Injector(config: Config, *, stage: Stage = Stage.DEVELOPMENT, parent: Injector | None = None, wire_private: bool = True)[source]

Bases: object

Resolves types and keys from a Config graph.

Why this exists: Manual wiring (new / factories everywhere) couples construction to call sites. The injector builds objects from bindings and constructor annotations so you register once and request by type. Catalog helpers (catalog_keys(), named_keys()) list membership without constructing plugins — see the module docstring for CLI / facade walkthroughs.

Example

>>> from pyiv import Config, get_injector
>>> class Database:
...     pass
>>> class PostgreSQL(Database):
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         self.register(Database, PostgreSQL)
>>> injector = get_injector(MyConfig)
>>> isinstance(injector.inject(Database), PostgreSQL)
True
__init__(config: Config, *, stage: Stage = Stage.DEVELOPMENT, parent: Injector | None = None, wire_private: bool = True)[source]

Initialize the injector with a configuration.

Parameters:
  • config – The configuration object that defines dependencies

  • stage – DEVELOPMENT (lazy) or PRODUCTION (eager singletons)

  • parent – Optional parent injector for hierarchical lookup

  • wire_private – If True, install pending PrivateConfig modules

catalog_keys(value_type: Type[T]) → List[Any][source]

Return map-multibind catalog keys for value_type without constructing.

Reads the local config’s map multibinding (implementation and instance maps). Does not call inject(). Empty list when nothing is bound.

Keys are sorted when all are mutually comparable; otherwise insertion order is preserved (implementations first, then instance-only keys).

Example

>>> from pyiv import Config, get_injector
>>> class Tool:
...     def __init__(self):
...         raise RuntimeError("must not construct for listing")
>>> class GrepTool(Tool):
...     def __init__(self):
...         pass
>>> class LintTool(Tool):
...     def __init__(self):
...         pass
>>> class ToolConfig(Config):
...     def configure(self):
...         mb = self.map_multibinder(Tool)
...         mb.add("lint", LintTool)
...         mb.add("grep", GrepTool)
>>> get_injector(ToolConfig).catalog_keys(Tool)
['grep', 'lint']
create_child(config: Type[Config] | Config) → Injector[source]

Create a child injector that inherits parent bindings.

The child sees parent bindings on miss; the parent cannot see child bindings. Singletons created in the child are local to the child.

Example

>>> from pyiv import Config, get_injector
>>> class Database:
...     pass
>>> class ProdConfig(Config):
...     def configure(self):
...         self.register(Database, Database)
>>> class RequestId:
...     def __init__(self, value: str = "r1"):
...         self.value = value
>>> class RequestConfig(Config):
...     def configure(self):
...         self.register(RequestId, RequestId)
>>> root = get_injector(ProdConfig)
>>> child = root.create_child(RequestConfig)
>>> isinstance(child.inject(Database), Database)
True
>>> child.inject(RequestId).value
'r1'
eager_singletons() → None[source]

Create all singleton-scoped bindings now (used by Stage.PRODUCTION).

inject(cls_or_key: Type | Key[Any], **kwargs) → Any[source]

Inject and create an instance of the given class or key.

Resolution for types (bare ``inject(Encoder)``):

  1. Unqualified registration / instance / provider for the type

  2. Else Named bindings for that type: the sole default=True binding, or the only Named binding if there is exactly one; multiple Named bindings without a unique default raise

  3. Else parent injector (if any)

  4. Else JIT for concrete types (unless explicit bindings required)

Resolution for keys:

  • Key(T, Named(...)) — strict exact tag-set match

  • Key(T, Matched(required=..., prefer=...)) — nearest match among Named bindings (required ⊆ tags, max prefer overlap, then default)

  • Custom qualifiers — exact Key lookup only

Ambiguous Named resolution raises CreationError (including when resolving Optional[T] constructor deps — ambiguity is not absence).

Constructor parameters may use Annotated with Named or Matched (and optionally Provider[T] / Optional[T]) on Python 3.9+ (or with typing_extensions.Annotated on 3.8). Annotated qualifiers apply only when resolving constructor / factory parameters — not on inject_members fields, not as the argument to inject() itself, and Matched is never valid at registration. See the keys guide for full examples.

Parameters:
  • cls_or_key – The class to instantiate or a Key

  • **kwargs – Additional keyword arguments to pass to the constructor

Returns:

An instance of the class (or registered concrete implementation)

Raises:

CreationError – If the binding cannot be resolved (with path context)

Example

>>> from pyiv import Config, get_injector
>>> from pyiv.key import Key, Named, Matched
>>> class Encoder:
...     def __init__(self, kind: str = "base"):
...         self.kind = kind
>>> class JSONEncoder(Encoder):
...     def __init__(self):
...         super().__init__("json")
>>> class PrettyJSONEncoder(Encoder):
...     def __init__(self):
...         super().__init__("pretty")
>>> class C(Config):
...     def configure(self):
...         self.register_key(Key(Encoder, Named("json")), JSONEncoder)
...         self.register_key(
...             Key(Encoder, Named(["json", "pretty"], default=True)),
...             PrettyJSONEncoder,
...         )
>>> inj = get_injector(C)
>>> inj.inject(Key(Encoder, Named("json"))).kind
'json'
>>> inj.inject(Key(Encoder, Matched(required=["json"], prefer=["pretty"]))).kind
'pretty'
>>> inj.inject(Encoder).kind
'pretty'
inject_by_name(interface: Type, name: str) → Type[source]

Inject a specific implementation by name (ReflectionConfig).

inject_chain_handler(chain_type: ChainType, handler_type: str) → ChainHandler[source]

Inject a chain handler instance by handler type.

inject_chain_handler_by_name(chain_type: ChainType, name: str) → ChainHandler[source]

Inject a chain handler instance by name.

inject_members(instance: Any) → None[source]

Inject dependencies into an existing instance.

Resolves bare field type annotations only. Annotated[T, Named] / Matched on fields is ignored — use constructor Annotated params or assign self.inject(Key(...)) manually.

named_keys(binding_type: Type[T]) → List[Named][source]

Return Named qualifiers bound for binding_type without constructing.

Lists Named-qualified keys from the local config (same store used by Matched resolution). Does not construct implementations. Order is stable by sorted tag tuples.

Example

>>> from pyiv import Config, get_injector
>>> from pyiv.key import Key, Named
>>> class Encoder:
...     def encode(self, data: str) -> str:
...         raise NotImplementedError
>>> class JsonEncoder(Encoder):
...     def encode(self, data: str) -> str:
...         return f"json:{data}"
>>> class XmlEncoder(Encoder):
...     def encode(self, data: str) -> str:
...         return f"xml:{data}"
>>> class NamedCatalogConfig(Config):
...     def configure(self):
...         self.register_key(Key(Encoder, Named("json")), JsonEncoder)
...         self.register_key(Key(Encoder, Named("xml")), XmlEncoder)
>>> tags = [
...     sorted(n.tags) for n in get_injector(NamedCatalogConfig).named_keys(Encoder)
... ]
>>> tags
[['json'], ['xml']]
property parent: Injector | None

Return the parent injector, if any.

property stage: Stage

Return the stage this injector was created with.

class pyiv.InjectorMembersInjector(cls: Type[T], injector: Any)[source]

Bases: Generic[T]

MembersInjector that fills fields on instances you already constructed.

Why this exists: Frameworks and legacy code often create objects outside the injector. Use this (or injector.inject_members) when constructor injection is impractical—dataclasses, third-party types, or migration.

Supports field injection (dataclasses, attrs, regular classes) and method injection for annotated methods.

Does not honor Annotated[T, Named(...)] / Matched(...) on fields. Those work on constructor parameters only; for qualified fields call injector.inject(Key(...)) and assign the result.

Example

>>> from pyiv.members import InjectorMembersInjector
>>> from dataclasses import dataclass, field
>>> from pyiv import Config, get_injector
>>>
>>> class Database:
...     pass
>>>
>>> @dataclass
... class Service:
...     db: Database = field(default=None)
>>>
>>> class MyConfig(Config):
...     def configure(self):
...         self.register(Database, Database)
>>>
>>> injector = get_injector(MyConfig)
>>> members_injector = InjectorMembersInjector(Service, injector)
>>> service = Service()
>>> members_injector.inject_members(service)
>>> isinstance(service.db, Database)
True
__init__(cls: Type[T], injector: Any)[source]

Initialize members injector.

Parameters:
  • cls – The class type to inject into

  • injector – The injector to use for dependency resolution

inject_members(instance: T) → None[source]

Inject dependencies into an existing instance.

This method: 1. Inspects the class for fields with type annotations 2. Resolves dependencies using the injector 3. Sets field values on the instance 4. Optionally calls methods with injected dependencies

Parameters:

instance – The instance to inject dependencies into

Raises:

TypeError – If instance is not of the expected type

class pyiv.InjectorProvider(cls_or_key: Type[T] | Key[T], injector: Any)[source]

Bases: Generic[T]

Provider that uses an injector to create instances.

This provider wraps an injector and a type or Key, delegating instance creation to the injector. Useful for lazy lookup and for Annotated[Provider[T], Named(...)] constructor params (field / members injection does not unwrap that Annotated form).

Why this exists: Provider that asks an Injector for T (or a qualified Key) on each get() — lazy graph lookup.

Example

>>> from pyiv import Config, get_injector
>>> from pyiv.key import Key, Named
>>> from pyiv.provider import InjectorProvider
>>>
>>> class Database:
...     def __init__(self, name: str = "default"):
...         self.name = name
>>>
>>> class PostgreSQL(Database):
...     def __init__(self):
...         super().__init__("postgresql")
>>>
>>> class MyConfig(Config):
...     def configure(self):
...         self.register(Database, Database)
...         self.register_key(Key(Database, Named("primary")), PostgreSQL)
>>>
>>> injector = get_injector(MyConfig)
>>> db_provider = InjectorProvider(Database, injector)
>>> isinstance(db_provider.get(), Database)
True
>>> named = InjectorProvider(Key(Database, Named("primary")), injector)
>>> named.get().name
'postgresql'
__init__(cls_or_key: Type[T] | Key[T], injector: Any)[source]

Initialize provider with a type or Key and injector.

Parameters:
  • cls_or_key – The type or qualified Key to provide instances of

  • injector – The injector to use for instance creation

get() → T[source]

Get an instance using the injector.

Returns:

An instance created by injector.inject of the type or Key

class pyiv.InstanceProvider(instance: T)[source]

Bases: Generic[T]

Provider that returns a pre-created instance.

Why this exists: Wrap an already-built object as a Provider for binder.to_provider / register_provider.

This provider simply returns the same instance every time get() is called. Useful for wrapping pre-created singletons or instances.

Example

>>> from pyiv.provider import InstanceProvider
>>>
>>> class Logger:
...     def __init__(self, name: str):
...         self.name = name
>>>
>>> my_logger = Logger("app")
>>> logger_provider = InstanceProvider(my_logger)
>>> logger = logger_provider.get()  # Returns my_logger
>>> logger is my_logger
True
>>> logger.name
'app'
__init__(instance: T)[source]

Initialize provider with a pre-created instance.

Parameters:

instance – The instance to return

get() → T[source]

Get the pre-created instance.

Returns:

The instance that was provided during initialization

exception pyiv.InvalidSpecifier[source]

Bases: InvalidVersion

Raised when a version constraint / specifier string is invalid.

Why this exists: Distinguishes bad constraints (>>>>1.0) from bad version strings while remaining catchable as InvalidVersion.

Example

>>> from pyiv.version import InvalidSpecifier, InvalidVersion
>>> issubclass(InvalidSpecifier, InvalidVersion)
True
exception pyiv.InvalidVersion[source]

Bases: ValueError

Base error for VersionParser parse and match failures.

Why this exists: Call sites and the injector need one exception type for “this version string / specifier is unusable,” regardless of whether the active parser is PEP 440, an OS-release grammar, or a host-defined schema epoch. Custom parsers should raise this class or a subclass.

Example

>>> from pyiv.version import InvalidVersion
>>> raise InvalidVersion("not a version")
Traceback (most recent call last):
...
pyiv.version.InvalidVersion: not a version
class pyiv.JSONSerDe[source]

Bases: SerDe

Standard JSON SerDe using Python’s json module.

Use this for APIs, configs, and payloads that exchange JSON. Datetimes serialize to ISO strings; objects with __dict__ become dicts. Prefer this over pickle whenever the data is text-safe and interoperable.

Example

>>> from pyiv.serde.encodings import JSONSerDe
>>> serde = JSONSerDe()
>>> serde.handler_type
'json'
>>> serde.serialize({"a": 1})
'{"a": 1}'
>>> serde.deserialize('{"a": 1}')
{'a': 1}
deserialize(data: str | bytes, target_type: Type[T] | None = None) → T[source]

Deserialize JSON string/bytes back to a Python object.

Parameters:
  • data – The JSON string or bytes

  • target_type – Optional type hint for the expected result type

Returns:

Deserialized Python object

property handler_type: str

Return the handler type identifier.

Returns:

The handler type identifier (“json”)

serialize(obj: Any) → str[source]

Serialize using standard JSON encoding.

Parameters:

obj – The Python object to serialize

Returns:

JSON string representation

class pyiv.Key(binding_type: Type[T], qualifier: Qualifier | None = None)[source]

Bases: Generic[T]

Type-safe key for qualified bindings.

Why this exists: Pair a type with an optional qualifier so multiple implementations of one type can coexist. Use Named when binding (and for strict inject). Use Matched only when injecting for nearest-match resolution.

Prefer Annotated[T, Named|Matched] on constructors when the dependency is a parameter; use inject(Key(...)) for explicit lookups. Annotated qualifiers are not applied during inject_members field injection.

Example

>>> from pyiv.key import Key, Named
>>>
>>> default_key = Key(int)
>>> primary_key = Key(int, Named("primary"))
>>> replica_key = Key(int, Named("replica"))
>>> primary_key != replica_key
True
>>> Key(int, Named("a")) == Key(int, Named(["a"]))
True
__init__(binding_type: Type[T], qualifier: Qualifier | None = None)[source]

Initialize a key.

Parameters:
  • binding_type – The type to bind

  • qualifier – Optional qualifier (Named for register/strict inject, Matched for inject-only nearest match)

Raises:

TypeError – If binding_type is not a type

class pyiv.ListMultibinder(interface: Type[T], config: Any)[source]

Bases: Generic[T]

Multibinder that binds to a List[T].

Why this exists: Collect implementations as List[T] preserving add order.

This multibinder collects implementations into a list, preserving order. Duplicates are allowed.

Example

>>> from pyiv import Config
>>>
>>> class Validator:
...     pass
>>> class EmailValidator(Validator):
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         pass
>>> multibinder = ListMultibinder(Validator, MyConfig())
>>> multibinder.add(EmailValidator)
>>> EmailValidator in multibinder.get_implementations()
True
__init__(interface: Type[T], config: Any)[source]

Initialize list multibinder.

Parameters:
  • interface – The interface type

  • config – The config to register bindings with

add(implementation: Type[T]) → None[source]

Add an implementation class.

Parameters:

implementation – The implementation class to add

add_instance(instance: T) → None[source]

Add a pre-created instance.

Parameters:

instance – The instance to add

get_implementations() → List[Type[T]][source]

Get all registered implementation classes.

Returns:

List of implementation classes (order preserved)

get_instances() → List[T][source]

Get all registered instances.

Returns:

List of instances (order preserved)

class pyiv.LogOptions(level: str = 'WARNING', verbose: int = 0, quiet: bool = False, format_style: str = 'short', allow_prefixes: ~typing.Tuple[str, ...] = (), deny_prefixes: ~typing.Tuple[str, ...] = (), logger_levels: ~typing.Mapping[str, str] = <factory>)[source]

Bases: object

Configuration for LogSetup.apply.

Why this exists: CLI flags and host Settings need a boring frozen bag — not dictConfig sprawl — without a pydantic dependency.

Example

>>> opts = LogOptions(level="DEBUG", verbose=1)
>>> opts.as_dict()["level"]
'DEBUG'
__init__(level: str = 'WARNING', verbose: int = 0, quiet: bool = False, format_style: str = 'short', allow_prefixes: ~typing.Tuple[str, ...] = (), deny_prefixes: ~typing.Tuple[str, ...] = (), logger_levels: ~typing.Mapping[str, str] = <factory>) → None
allow_prefixes: Tuple[str, ...] = ()
as_dict() → Dict[str, Any][source]
deny_prefixes: Tuple[str, ...] = ()
effective_level() → str[source]

Resolve level from quiet / verbose / explicit level.

format_style: str = 'short'
classmethod from_dict(data: Mapping[str, Any]) → LogOptions[source]
level: str = 'WARNING'
logger_levels: Mapping[str, str]
quiet: bool = False
verbose: int = 0
class pyiv.LogSetup(stream=None)[source]

Bases: object

Configure root logging from LogOptions (idempotent replace).

Why this exists: CLI -v / --log-level should apply once without fighting duplicate handlers or hand-rolled basicConfig.

Example

>>> from pyiv.log import LogOptions, LogSetup
>>> LogSetup().apply(LogOptions(level="INFO", format_style="short"))
__init__(stream=None) → None[source]
apply(options: LogOptions) → None[source]

Replace pyiv-managed root handlers with options-derived config.

class pyiv.Logger[source]

Bases: ABC

Injectable diagnostic logger.

Why this exists: Services should not call logging.getLogger directly if tests need to assert messages without patching the logging module.

Example

>>> from pyiv.log import MemoryLogger
>>> log: Logger = MemoryLogger("svc")
>>> log.info("ready")
>>> log.records[-1].message
'ready'
abstract debug(msg: str, *args: Any, **kwargs: Any) → None[source]

Log a debug message.

abstract error(msg: str, *args: Any, **kwargs: Any) → None[source]

Log an error message.

abstract exception(msg: str, *args: Any, **kwargs: Any) → None[source]

Log an error with exception info.

abstract info(msg: str, *args: Any, **kwargs: Any) → None[source]

Log an info message.

log(level: int, msg: str, *args: Any, **kwargs: Any) → None[source]

Log at a numeric level (default routes through info for Memory).

abstract warning(msg: str, *args: Any, **kwargs: Any) → None[source]

Log a warning message.

class pyiv.LoggerFactory[source]

Bases: ABC

Create named Logger instances.

Why this exists: Services ask for a named logger without binding each name in the injector.

Example

>>> from pyiv.log import StdlibLoggerFactory
>>> factory: LoggerFactory = StdlibLoggerFactory()
>>> isinstance(factory.get("app.svc"), Logger)
True
abstract get(name: str | Type[Any]) → Logger[source]

Return a logger for name (string or type).

class pyiv.MapMultibinder(value_type: Type[V], config: Any)[source]

Bases: Generic[K, V]

Multibinder that binds to a Dict[K, V].

Why this exists: Collect keyed implementations for Dict[K, V] injection (plugin / recipe catalogs). Inject the dict through a host class constructor, not injector.inject(Dict[...]). For host extension with an explicit conflict policy, prefer contribute_map().

Example

>>> from typing import Dict
>>> from pyiv import Config, get_injector
>>> class Plugin:
...     pass
>>> class AuthPlugin(Plugin):
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         self.map_multibinder(Plugin).add("auth", AuthPlugin)
>>> class Host:
...     def __init__(self, plugins: Dict[str, Plugin]):
...         self.plugins = plugins
>>> "auth" in get_injector(MyConfig).inject(Host).plugins
True
__init__(value_type: Type[V], config: Any)[source]
add(key: K, implementation: Type[V]) → None[source]

Add a keyed implementation class.

add_instance(key: K, instance: V) → None[source]

Add a keyed pre-created instance.

get_implementations() → Dict[K, Type[V]][source]

Get all registered keyed implementation classes.

get_instances() → Dict[K, V][source]

Get all registered keyed instances.

class pyiv.MapVersionSource(versions: Mapping[str, str], *, domain: str | None = None)[source]

Bases: object

Fixed version map for tests and host-supplied environment snapshots.

Why this exists: Selection must be deterministic in unit tests without monkeypatching sys or importlib.metadata. Use it for for_package_version ranges and to simulate an installed distribution for for_package_present (register under package_version_domain()). Bind one domain key, or pass a multi-key map and select with domain.

Example

>>> from pyiv.version import MapVersionSource, package_version_domain
>>> MapVersionSource({"requests": "2.31.0"}, domain="requests").get_version()
'2.31.0'
>>> MapVersionSource({"alpine": "3.19"}).get_version()
'3.19'
>>> domain = package_version_domain("cjson")
>>> MapVersionSource({domain: "1.0.0"}).get_version()
'1.0.0'
__init__(versions: Mapping[str, str], *, domain: str | None = None) → None[source]
Parameters:
  • versions – Mapping of domain name → version string.

  • domain – Domain to read. When omitted and versions has exactly one entry, that entry is used.

get_version() → str | None[source]

Return the configured version for this source’s domain, if any.

class pyiv.MappingFilesystem(data: Mapping[str, str | bytes] | None = None)[source]

Bases: Filesystem

Expose a string→bytes (or str) mapping as a flat file tree under /.

Why this exists: Pattern for external adapters (DB row as /proc file) without putting SQL in core. Mount under MountFilesystem.

Example

>>> from pyiv.files import MappingFilesystem, MountFilesystem, MemoryFilesystem
>>> proc = MappingFilesystem({"uptime": "1.0", "version": "pyiv"})
>>> fs = MountFilesystem(MemoryFilesystem())
>>> fs.mount("/proc", proc)
>>> fs.read_text("/proc/uptime")
'1.0'
__init__(data: Mapping[str, str | bytes] | None = None) → None[source]
copy(src: str | Path, dst: str | Path) → None[source]

Copy a file.

Parameters:
  • src – Source path

  • dst – Destination path

exists(path: str | Path) → bool[source]

Check if a path exists.

Parameters:

path – Path to check

Returns:

True if path exists, False otherwise

get_size(path: str | Path) → int[source]

Get file size in bytes.

Parameters:

path – File path

Returns:

File size in bytes

glob(pattern: str | Path) → Iterator[Path][source]

Glob pattern matching.

Parameters:

pattern – Glob pattern

Yields:

Matching paths

is_dir(path: str | Path) → bool[source]

Check if path is a directory.

Parameters:

path – Path to check

Returns:

True if path is a directory, False otherwise

is_file(path: str | Path) → bool[source]

Check if path is a file.

Parameters:

path – Path to check

Returns:

True if path is a file, False otherwise

listdir(path: str | Path) → Iterator[str][source]

List directory contents.

Parameters:

path – Directory path

Yields:

Directory entry names

mkdir(path: str | Path, parents: bool = False, exist_ok: bool = False) → None[source]

Create a directory.

Parameters:
  • path – Directory path

  • parents – Create parent directories if needed

  • exist_ok – Don’t raise error if directory exists

move(src: str | Path, dst: str | Path) → None[source]

Move/rename a file or directory.

Parameters:
  • src – Source path

  • dst – Destination path

open(file: str | Path, mode: str = 'r', encoding: str | None = None) → TextIO | BinaryIO[source]

Open a file.

Parameters:
  • file – File path

  • mode – File mode (r, w, a, rb, wb, etc.)

  • encoding – Text encoding (for text modes)

Returns:

File handle

read_bytes(path: str | Path) → bytes[source]

Read bytes from a file.

Parameters:

path – File path

Returns:

File contents as bytes

read_text(path: str | Path, encoding: str = 'utf-8') → str[source]

Read text from a file.

Parameters:
  • path – File path

  • encoding – Text encoding

Returns:

File contents as string

rmdir(path: str | Path) → None[source]

Remove a directory.

Parameters:

path – Directory path

Remove a file.

Parameters:
  • path – File path

  • missing_ok – Don’t raise error if file doesn’t exist

write_bytes(path: str | Path, content: bytes) → None[source]

Write bytes to a file.

Parameters:
  • path – File path

  • content – Bytes content to write

write_text(path: str | Path, content: str, encoding: str = 'utf-8') → None[source]

Write text to a file.

Parameters:
  • path – File path

  • content – Text content to write

  • encoding – Text encoding

class pyiv.Matched(required: str | Sequence[str] | None = None, prefer: str | Sequence[str] | None = None)[source]

Bases: object

Inject-only qualifier for required/prefer tag matching.

Why this exists: Exact Named keys are rigid when several bindings share tags. Matched selects among Named registrations: every required tag must be present, then the binding with the most prefer overlap wins; Named(..., default=True) breaks remaining ties. Frozen dataclass shape stays pydantic-friendly without a pydantic dependency.

Do not pass Matched to register_key / bind_key — registration uses Named only.

Constructor injection: Annotated[T, Matched(...)] on __init__ (including Annotated[Optional[T], Matched(...)]). Not supported on field / inject_members paths.

Resolution ladder (candidates = all Named bindings for the key type):

  1. Keep bindings where required ⊆ binding.tags

  2. Keep those with maximal |prefer ∩ binding.tags|

  3. If still more than one, keep default=True

  4. Exactly one → use it; otherwise CreationError

Example

>>> from pyiv.key import Key, Named, Matched
>>> from pyiv import Config, get_injector
>>>
>>> class Encoder:
...     def __init__(self, kind: str):
...         self.kind = kind
>>>
>>> class JSONEncoder(Encoder):
...     def __init__(self):
...         super().__init__("json")
>>>
>>> class PrettyJSONEncoder(Encoder):
...     def __init__(self):
...         super().__init__("pretty")
>>>
>>> class C(Config):
...     def configure(self):
...         self.register_key(Key(Encoder, Named("json")), JSONEncoder)
...         self.register_key(
...             Key(Encoder, Named(["json", "pretty"], default=True)),
...             PrettyJSONEncoder,
...         )
>>>
>>> get_injector(C).inject(
...     Key(Encoder, Matched(required=["json"], prefer=["pretty"]))
... ).kind
'pretty'
__init__(required: str | Sequence[str] | None = None, prefer: str | Sequence[str] | None = None)[source]

Initialize matched qualifier.

Parameters:
  • required – Tags that must all be present on a candidate (optional)

  • prefer – Tags used to score candidates; more overlap wins (optional)

Raises:
prefer: FrozenSet[str]
required: FrozenSet[str]
class pyiv.MembersInjector(*args, **kwargs)[source]

Bases: Protocol, Generic[T]

Protocol for injecting dependencies into existing instances.

Why this exists: Inject into objects you did not construct (frameworks, dataclasses, legacy).

MembersInjectors inject dependencies into fields and methods of existing instances. This is useful for: - Framework integration (Django, Flask, etc.) - Legacy code migration - Third-party object injection - Field injection for data classes

Example

class MyMembersInjector(MembersInjector[Service]):
def inject_members(self, instance: Service) -> None:

instance.db = self._injector.inject(Database)

__init__(*args, **kwargs)
inject_members(instance: T) → None[source]

Inject dependencies into an existing instance.

Parameters:

instance – The instance to inject dependencies into

class pyiv.MemoryArgv(args: Sequence[str] | None = None)[source]

Bases: Argv

In-memory argv / exit capture for tests.

Why this exists: Drive CLI parsing without touching sys.

Example

>>> a = MemoryArgv(["tool", "-v"])
>>> a.exit(1)
>>> a.exit_status.code
1
__init__(args: Sequence[str] | None = None) → None[source]
property args: Sequence[str]

Program arguments including argv[0].

exit(code: int = 0) → None[source]

Request process exit with code.

class pyiv.MemoryAsyncHttpClient(base_url=None, headers=None, sync_client=None, options=None)[source]

Bases: AsyncHttpClient

Async memory HTTP client (same canned routes as MemoryHttpClient).

Why this exists: Async unit tests need the same fake without a live event-loop network stack.

Example

>>> import asyncio
>>> client = MemoryAsyncHttpClient()
>>> client.add("GET", "http://t/", body=b"x")
>>> asyncio.run(client.get("http://t/")).content
b'x'
__init__(base_url=None, headers=None, sync_client=None, options=None) → None[source]
add(method: str, url: str, **kwargs: Any) → None[source]
async request(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]

Send an HTTP request and return a buffered response.

property requests: List[RecordedRequest]
stream(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → AsyncIterator[AsyncStreamResponse][source]

Open an async streaming response (async context manager).

class pyiv.MemoryConsole[source]

Bases: BaseConsole

In-memory console for testing.

Why this exists: Capture print(…, file=console) without touching stdout.

This console stores output in memory, allowing tests to capture and verify console output without actually printing to stdout.

Example

>>> from pyiv.console import MemoryConsole
>>>
>>> console = MemoryConsole()
>>> print("Test message", file=console)
>>> print("Another line", file=console)
>>>
>>> # Get all captured output
>>> output = console.getvalue()
>>> assert "Test message" in output
>>> assert "Another line" in output
>>>
>>> # Clear and reuse
>>> console.seek(0)
0
>>> console.truncate(0)
0
>>> print("New output", file=console)
>>> console.getvalue()
'New output\n'
__init__()[source]

Initialize in-memory console.

close() → None[source]

Close the buffer.

Note: After closing, getvalue() will raise ValueError. To get the value before closing, call getvalue() first.

flush() → None[source]

Flush buffer (no-op for memory console).

getvalue() → str[source]

Get all captured output.

Returns:

All output written to the console as a string

seek(pos: int) → int[source]

Seek to position in buffer.

Parameters:

pos – Position to seek to

Returns:

New position

truncate(size: int | None = None) → int[source]

Truncate buffer to size.

Parameters:

size – Size to truncate to (None = current position)

Returns:

New size

writable() → bool[source]

Check if console is writable.

Returns:

True (memory console is always writable)

write(s: str) → int[source]

Write string to memory buffer.

Parameters:

s – String to write

Returns:

Number of characters written

class pyiv.MemoryEnvironment(initial: Mapping[str, str] | None = None)[source]

Bases: Environment

In-memory environment for tests.

Why this exists: Isolate env mutations without touching the process.

Example

>>> env = MemoryEnvironment({"HOME": "/tmp"})
>>> env.set("X", "1")
>>> env.as_dict()["X"]
'1'
__init__(initial: Mapping[str, str] | None = None) → None[source]
as_dict() → Dict[str, str][source]

Return a snapshot mapping.

get(key: str, default: str | None = None) → str | None[source]

Return the value for key, or default.

set(key: str, value: str) → None[source]

Set key to value.

unset(key: str) → None[source]

Remove key if present.

class pyiv.MemoryFilesystem[source]

Bases: Filesystem

In-memory filesystem for testing.

Use this whenever code under test needs file I/O but must not touch the real disk. Paths live in a dict-backed store, so tests stay fast and isolated.

Example

>>> from pyiv.files import MemoryFilesystem
>>> fs = MemoryFilesystem()
>>> fs.write_text("/notes/a.txt", "alpha")
>>> fs.mkdir("/notes/sub", parents=True, exist_ok=True)
>>> fs.exists("/notes/a.txt")
True
>>> fs.read_text("/notes/a.txt")
'alpha'
__init__()[source]

Initialize in-memory filesystem.

copy(src: str | Path, dst: str | Path) → None[source]

Copy a file.

Parameters:
  • src – Source file path

  • dst – Destination file path

Raises:

FileNotFoundError – If source file doesn’t exist

exists(path: str | Path) → bool[source]

Check if path exists.

Parameters:

path – Path to check

Returns:

True if path exists (as file or directory), False otherwise

get_size(path: str | Path) → int[source]

Get file size in bytes.

Parameters:

path – File path

Returns:

File size in bytes

Raises:

FileNotFoundError – If file doesn’t exist

glob(pattern: str | Path) → Iterator[Path][source]

Glob pattern matching (simplified).

Parameters:

pattern – Glob pattern to match

Yields:

Matching paths

is_dir(path: str | Path) → bool[source]

Check if path is a directory.

Parameters:

path – Path to check

Returns:

True if path is a directory, False otherwise

is_file(path: str | Path) → bool[source]

Check if path is a file.

Parameters:

path – Path to check

Returns:

True if path is a file, False otherwise

listdir(path: str | Path) → Iterator[str][source]

List directory contents.

Parameters:

path – Directory path to list

Yields:

Directory entry names

Raises:

FileNotFoundError – If directory doesn’t exist

mkdir(path: str | Path, parents: bool = False, exist_ok: bool = False) → None[source]

Create a directory.

Parameters:
  • path – Directory path to create

  • parents – Create parent directories if needed

  • exist_ok – Don’t raise error if directory already exists

Raises:
move(src: str | Path, dst: str | Path) → None[source]

Move/rename a file or directory.

Parameters:
  • src – Source path

  • dst – Destination path

Raises:

FileNotFoundError – If source doesn’t exist

open(file: str | Path, mode: str = 'r', encoding: str | None = None) → TextIO | BinaryIO[source]

Open a file in memory.

Parameters:
  • file – File path to open

  • mode – File mode (r, w, a, rb, wb, etc.)

  • encoding – Text encoding (for text modes, ignored for binary modes)

Returns:

File handle (TextIO for text modes, BinaryIO for binary modes)

Raises:
read_bytes(path: str | Path) → bytes[source]

Read bytes from a file.

Parameters:

path – File path to read

Returns:

File contents as bytes

Raises:

FileNotFoundError – If file doesn’t exist

read_text(path: str | Path, encoding: str = 'utf-8') → str[source]

Read text from a file.

Parameters:
  • path – File path to read

  • encoding – Text encoding (default: utf-8)

Returns:

File contents as string

Raises:

FileNotFoundError – If file doesn’t exist

rmdir(path: str | Path) → None[source]

Remove a directory.

Parameters:

path – Directory path to remove (must be empty)

Raises:

Remove a file.

Parameters:
  • path – File path to remove

  • missing_ok – Don’t raise error if file doesn’t exist

Raises:

FileNotFoundError – If file doesn’t exist and missing_ok is False

write_bytes(path: str | Path, content: bytes) → None[source]

Write bytes to a file.

Parameters:
  • path – File path to write

  • content – Bytes content to write

write_text(path: str | Path, content: str, encoding: str = 'utf-8') → None[source]

Write text to a file.

Parameters:
  • path – File path to write

  • content – Text content to write

  • encoding – Text encoding (default: utf-8)

class pyiv.MemoryHttpClient(base_url=None, headers=None, options=None)[source]

Bases: HttpClient

Sync HTTP client that returns canned responses (no network).

Why this exists: Doctests and unit tests must not hit the network. Recorded requests make assertions easy.

Example

>>> client = MemoryHttpClient()
>>> client.add("POST", "http://api.test/v1", json={"ok": True})
>>> client.post("http://api.test/v1", json={"n": 1}).json()
{'ok': True}
>>> client.requests[0].method
'POST'
__init__(base_url=None, headers=None, options=None) → None[source]
add(method: str, url: str, **kwargs: Any) → None[source]

Register a canned response. See _MemoryStore.add.

request(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]

Send an HTTP request and return a buffered response.

property requests: List[RecordedRequest]
stream(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → Iterator[StreamResponse][source]

Open a streaming response (context manager).

class pyiv.MemoryLogSetup[source]

Bases: object

No-op setup for tests that use MemoryLogger only.

Why this exists: Avoid attaching handlers when tests inject memory logs.

apply(options: LogOptions | None = None) → None[source]
class pyiv.MemoryLogger(name: str = 'memory')[source]

Bases: Logger

In-memory logger for tests.

Why this exists: Assert diagnostics without attaching handlers to root.

Example

>>> log = MemoryLogger("t")
>>> log.warning("careful")
>>> [r.level for r in log.records]
['WARNING']
__init__(name: str = 'memory') → None[source]
debug(msg: str, *args: Any, **kwargs: Any) → None[source]

Log a debug message.

error(msg: str, *args: Any, **kwargs: Any) → None[source]

Log an error message.

exception(msg: str, *args: Any, **kwargs: Any) → None[source]

Log an error with exception info.

info(msg: str, *args: Any, **kwargs: Any) → None[source]

Log an info message.

warning(msg: str, *args: Any, **kwargs: Any) → None[source]

Log a warning message.

class pyiv.MemoryLoggerFactory[source]

Bases: LoggerFactory

Factory that returns shared MemoryLogger instances by name.

Why this exists: Tests inject one factory and assert per-name records.

__init__() → None[source]
get(name: str | Type[Any]) → Logger[source]

Return a logger for name (string or type).

class pyiv.MemoryProcessRunner[source]

Bases: ProcessRunner

Scripted process runner for tests.

Why this exists: Assert argv and return canned results without spawning.

Example

>>> runner = MemoryProcessRunner()
>>> runner.script(["echo", "hi"], returncode=0, stdout="hi\n")
>>> runner.run(["echo", "hi"]).stdout
'hi\n'
__init__() → None[source]
run(argv: Sequence[str], *, options: RunOptions | None = None) → CompletedProcess[source]

Run argv and return a completed process result.

script(argv_prefix: Sequence[str], *, returncode: int = 0, stdout: str = '', stderr: str = '') → None[source]

Register a canned result when argv starts with argv_prefix.

set_default(handler: Callable[[Sequence[str]], CompletedProcess]) → None[source]
class pyiv.MockConsole(width: int = 80, height: int = 24)[source]

Bases: BaseConsole

Terminal state machine for testing.

This console maintains a complete terminal state including screen buffer, cursor position, colors, and input state. Use this for testing terminal functionality with full state inspection and event tracking.

Example

>>> from pyiv.console import MockConsole
>>>
>>> console = MockConsole(width=80, height=24)
>>> console.clear()
>>> console.move_cursor(10, 5)
>>> console.set_color(fg=31)  # Red
>>> console.write("Hello")
5
>>>
>>> console.get_cursor()
(15, 5)
>>> console.get_screen_line(5)[10:15]
'Hello'
>>> len(console.get_events())
4
__init__(width: int = 80, height: int = 24)[source]

Initialize terminal state machine.

Parameters:
  • width – Terminal width in columns

  • height – Terminal height in rows

bold(enabled: bool = True) → None[source]

Enable or disable bold text.

clear() → None[source]

Clear the entire screen.

clear_line() → None[source]

Clear the current line.

clear_state() → None[source]

Clear all state (for test setup).

clear_to_end_of_line() → None[source]

Clear from cursor to end of line.

flush() → None[source]

Flush buffer (no-op for mock console).

get_color() → Tuple[int | None, int | None][source]

Get current color state.

Returns:

Tuple of (fg, bg)

get_cursor() → Tuple[int, int][source]

Get current cursor position.

Returns:

Tuple of (x, y)

get_cursor_position() → Tuple[int, int] | None[source]

Get current cursor position.

Returns:

Tuple of (x, y)

get_echo_enabled() → bool[source]

Get echo state.

Returns:

True if echo is enabled

get_events() → List[TerminalEvent][source]

Get event history.

Returns:

List of terminal events

get_raw_mode() → bool[source]

Get raw mode state.

Returns:

True if raw mode is enabled

get_screen() → List[List[str]][source]

Get screen buffer (copy).

Returns:

2D list of screen contents

get_screen_char(x: int, y: int) → str[source]

Get character at position.

Parameters:
  • x – Column (0-based)

  • y – Row (0-based)

Returns:

Character at position

get_screen_line(y: int) → str[source]

Get specific line from screen.

Parameters:

y – Line number (0-based)

Returns:

Line contents as string

get_size() → Tuple[int, int][source]

Get terminal size.

Returns:

Tuple of (columns, rows)

get_style() → Dict[str, bool][source]

Get text style state.

Returns:

Dictionary of style flags

hide_cursor() → None[source]

Hide the cursor.

is_tty() → bool[source]

Check if console is a TTY (always False for mock).

Returns:

False (mock console is not a real TTY)

move_cursor(x: int, y: int) → None[source]

Move cursor to position.

move_cursor_down(n: int = 1) → None[source]

Move cursor down n lines.

move_cursor_home() → None[source]

Move cursor to home position.

move_cursor_left(n: int = 1) → None[source]

Move cursor left n columns.

move_cursor_right(n: int = 1) → None[source]

Move cursor right n columns.

move_cursor_up(n: int = 1) → None[source]

Move cursor up n lines.

read_char(timeout: float | None = None) → str | None[source]

Read a single character from input buffer.

Parameters:

timeout – Optional timeout in seconds (ignored for MockConsole)

Returns:

Character string or None if no input available

read_line(prompt: str = '') → str[source]

Read a line from input buffer.

Parameters:

prompt – Optional prompt string to display

Returns:

Line of text (without newline)

read_password(prompt: str = '') → str[source]

Read password with echo disabled.

reset_color() → None[source]

Reset colors to default.

restore_cursor() → None[source]

Restore saved cursor position.

save_cursor() → None[source]

Save current cursor position.

set_color(fg: int | None = None, bg: int | None = None) → None[source]

Set foreground and/or background color.

set_echo(enabled: bool) → None[source]

Turn echo on/off for password prompts.

set_raw_mode(enabled: bool) → None[source]

Enable/disable raw mode.

show_cursor() → None[source]

Show the cursor.

simulate_input(text: str) → None[source]

Simulate input for testing.

Parameters:

text – Text to add to input buffer

underline(enabled: bool = True) → None[source]

Enable or disable underline.

writable() → bool[source]

Check if console is writable.

Returns:

True (mock console is always writable)

write(s: str) → int[source]

Write string, parsing escape sequences and updating state.

Parameters:

s – String to write

Returns:

Number of characters written

class pyiv.MockDateTimeService(fixed_time: datetime | None = None)[source]

Bases: DateTimeService

Mock datetime service for testing.

Why this exists: Freeze calendar time for deterministic tests of ISO/UTC stamps.

This implementation allows you to control the time returned, making it easy to test time-dependent code with predictable timestamps.

Example

>>> from datetime import datetime, timezone
>>> service = MockDateTimeService(datetime(2024, 1, 15, 10, 30, 0, tzinfo=timezone.utc))
>>> service.now_utc().isoformat()
'2024-01-15T10:30:00+00:00'
>>> service.set_time(datetime(2024, 1, 16, 12, 0, 0, tzinfo=timezone.utc))
>>> service.now_utc().isoformat()
'2024-01-16T12:00:00+00:00'
__init__(fixed_time: datetime | None = None)[source]

Initialize with optional fixed time.

Parameters:

fixed_time – Fixed datetime to return (defaults to current time if not provided)

now_utc() → datetime[source]

Return fixed time.

Returns:

The fixed datetime set for this mock service

now_utc_iso() → str[source]

Return fixed time as ISO string.

Returns:

The fixed datetime as ISO format string

set_time(new_time: datetime) → None[source]

Set the fixed time.

Parameters:

new_time – New fixed time. If no timezone is provided, UTC is assumed.

class pyiv.MountFilesystem(root: Filesystem | None = None)[source]

Bases: Filesystem

Path-prefix router over nested Filesystem instances.

Why this exists: Expose virtual trees (fake /proc, zip mounts, etc.) beside a real or memory root without monkeypatching open.

Example

>>> from pyiv.files import MemoryFilesystem, MountFilesystem
>>> root = MemoryFilesystem()
>>> root.write_text("/data/a.txt", "a")
>>> proc = MemoryFilesystem()
>>> proc.write_text("/status", "ok")
>>> fs = MountFilesystem(root)
>>> fs.mount("/proc", proc)
>>> fs.read_text("/data/a.txt")
'a'
>>> fs.read_text("/proc/status")
'ok'
__init__(root: Filesystem | None = None) → None[source]
copy(src: str | Path, dst: str | Path) → None[source]

Copy a file.

Parameters:
  • src – Source path

  • dst – Destination path

exists(path: str | Path) → bool[source]

Check if a path exists.

Parameters:

path – Path to check

Returns:

True if path exists, False otherwise

get_size(path: str | Path) → int[source]

Get file size in bytes.

Parameters:

path – File path

Returns:

File size in bytes

glob(pattern: str | Path) → Iterator[Path][source]

Glob pattern matching.

Parameters:

pattern – Glob pattern

Yields:

Matching paths

is_dir(path: str | Path) → bool[source]

Check if path is a directory.

Parameters:

path – Path to check

Returns:

True if path is a directory, False otherwise

is_file(path: str | Path) → bool[source]

Check if path is a file.

Parameters:

path – Path to check

Returns:

True if path is a file, False otherwise

listdir(path: str | Path) → Iterator[str][source]

List directory contents.

Parameters:

path – Directory path

Yields:

Directory entry names

mkdir(path: str | Path, parents: bool = False, exist_ok: bool = False) → None[source]

Create a directory.

Parameters:
  • path – Directory path

  • parents – Create parent directories if needed

  • exist_ok – Don’t raise error if directory exists

mount(mount_path: str | Path, filesystem: Filesystem) → None[source]

Mount filesystem at mount_path (longest prefix wins).

move(src: str | Path, dst: str | Path) → None[source]

Move/rename a file or directory.

Parameters:
  • src – Source path

  • dst – Destination path

open(file: str | Path, mode: str = 'r', encoding: str | None = None) → TextIO | BinaryIO[source]

Open a file.

Parameters:
  • file – File path

  • mode – File mode (r, w, a, rb, wb, etc.)

  • encoding – Text encoding (for text modes)

Returns:

File handle

read_bytes(path: str | Path) → bytes[source]

Read bytes from a file.

Parameters:

path – File path

Returns:

File contents as bytes

read_text(path: str | Path, encoding: str = 'utf-8') → str[source]

Read text from a file.

Parameters:
  • path – File path

  • encoding – Text encoding

Returns:

File contents as string

rmdir(path: str | Path) → None[source]

Remove a directory.

Parameters:

path – Directory path

Remove a file.

Parameters:
  • path – File path

  • missing_ok – Don’t raise error if file doesn’t exist

unmount(mount_path: str | Path) → None[source]

Remove a mount by path prefix.

write_bytes(path: str | Path, content: bytes) → None[source]

Write bytes to a file.

Parameters:
  • path – File path

  • content – Bytes content to write

write_text(path: str | Path, content: str, encoding: str = 'utf-8') → None[source]

Write text to a file.

Parameters:
  • path – File path

  • content – Text content to write

  • encoding – Text encoding

class pyiv.MountPoint(mount_path: str, filesystem: Filesystem)[source]

Bases: object

A path prefix bound to a nested filesystem.

Why this exists: Frozen knob for mount tables (Settings-friendly).

Example

>>> from pyiv.files import MemoryFilesystem, MountPoint
>>> MountPoint("/proc", MemoryFilesystem()).mount_path
'/proc'
__init__(mount_path: str, filesystem: Filesystem) → None
filesystem: Filesystem
mount_path: str
class pyiv.Multibinder(*args, **kwargs)[source]

Bases: Protocol, Generic[T]

Protocol for binding multiple implementations of the same type.

Why this exists: Register many implementations of one type for injection as a collection.

Multibinders allow multiple implementations of the same type to be registered and injected as a collection (Set or List).

Example

class MyMultibinder(Multibinder[EventHandler]):
def add(self, implementation: Type[EventHandler]) -> None:

# Register implementation pass

__init__(*args, **kwargs)
add(implementation: Type[T]) → None[source]

Add an implementation to the multibinding.

Parameters:

implementation – The implementation class to add

add_instance(instance: T) → None[source]

Add a pre-created instance to the multibinding.

Parameters:

instance – The instance to add

class pyiv.Named(name: str | Sequence[str], *, default: bool = False)[source]

Bases: object

Tag-set qualifier for named bindings (registration and strict inject).

Why this exists: Distinguish multiple implementations of one type with string tags. A scalar name is the common case; list/tuple tags form a set for compound keys. default=True marks the binding used for bare inject(Type) and for Matched tie-breaks. Frozen dataclass shape stays pydantic-friendly without a pydantic dependency.

Accepts str, list, or tuple; all normalize to a frozenset. Named("json") == Named(["json"]). Equality and hashing use the tag set only — default is binding metadata, not part of key identity.

Register with Named only. For nearest-match inject, use Matched.

Constructor injection: use Annotated[T, Named(...)] on __init__ parameters (also with Optional[T] / Provider[T]). This does not apply to field / inject_members injection — see the keys guide.

Example

>>> from pyiv.key import Named
>>>
>>> Named("primary") == Named(["primary"])
True
>>> Named(["json", "pretty"]).tags == frozenset({"json", "pretty"})
True
>>> Named("x", default=True) == Named("x", default=False)
True
__init__(name: str | Sequence[str], *, default: bool = False)[source]

Initialize named qualifier.

Parameters:
  • name – A non-empty string, or a non-empty list/tuple of tag strings

  • default – If True, this binding is preferred for bare type inject and breaks ties under Matched

Raises:
  • TypeError – If tags are not strings or name is not str/list/tuple

  • ValueError – If tags are empty

default: bool = False
name: str = ''
tags: FrozenSet[str]
class pyiv.NoOpSerDe[source]

Bases: SerDe

No-op SerDe that passes through data unchanged.

Use this as the default when no encoding is configured, or when a pipeline already holds strings/bytes and must not re-encode them. Strings and bytes are returned as-is; other objects become str(obj).

Why this exists: Default pass-through encoder when no wire format was configured.

Example

>>> from pyiv.serde.encodings import NoOpSerDe
>>> serde = NoOpSerDe()
>>> serde.handler_type
'noop'
>>> serde.serialize("already-encoded")
'already-encoded'
>>> serde.deserialize("already-encoded")
'already-encoded'
deserialize(data: str | bytes, target_type: Type[T] | None = None) → T[source]

Pass through the data unchanged.

Parameters:
  • data – The encoded data (string or bytes)

  • target_type – Optional type hint (ignored)

Returns:

The data unchanged

property handler_type: str

Return the handler type identifier.

Returns:

The handler type identifier (“noop”)

serialize(obj: Any) → str | bytes[source]

Pass through the object unchanged.

Parameters:

obj – The Python object to serialize

Returns:

The object unchanged (as string or bytes)

class pyiv.NoScope[source]

Bases: object

No scope - creates a new instance every time.

Why this exists: Explicit unscoped binding when a type annotation would otherwise imply reuse.

This scope does not cache instances. Each call to get() will create a new instance. This is the default behavior when no scope is specified.

Example

>>> from pyiv.scope import NoScope
>>> from pyiv import Config
>>>
>>> class MyConfig(Config):
...     def configure(self):
...         # No caching - new instance every time
...         self.register(Logger, FileLogger, scope=NoScope())
scope(key: Type | str | tuple, provider: Provider[Any]) → Provider[Any][source]

Return the provider unchanged (no caching).

Parameters:
  • key – The key identifying the dependency

  • provider – The provider to scope

Returns:

The same provider (no caching)

class pyiv.OsEnvironment[source]

Bases: Environment

Environment backed by os.environ.

Why this exists: Production binding for real process env.

as_dict() → Dict[str, str][source]

Return a snapshot mapping.

get(key: str, default: str | None = None) → str | None[source]

Return the value for key, or default.

set(key: str, value: str) → None[source]

Set key to value.

unset(key: str) → None[source]

Remove key if present.

class pyiv.PTYConsole[source]

Bases: BaseConsole

Pseudoterminal console for testing.

This console creates a pseudoterminal (pty) that behaves like a real terminal. Use this for testing programs that require TTY behavior.

Example

>>> from pyiv.console import PTYConsole
>>>
>>> try:
...     with PTYConsole() as console:
...         assert console.is_tty() is True
...         _ = console.write("Test")
... except (OSError, RuntimeError):
...     pass  # pty may be unavailable in sandbox/CI environments
__init__()[source]

Initialize pseudoterminal console.

bold(enabled: bool = True) → None[source]

Enable or disable bold text.

clear() → None[source]

Clear the entire screen.

clear_line() → None[source]

Clear the current line.

clear_state() → None[source]

Clear all state (no-op for PTYConsole).

clear_to_end_of_line() → None[source]

Clear from cursor to end of line.

close() → None[source]

Close the pty.

flush() → None[source]

Flush pty buffer.

get_color() → Tuple[int | None, int | None][source]

Get color state (not available).

get_cursor() → Tuple[int, int][source]

Get cursor position (not available).

get_cursor_position() → Tuple[int, int] | None[source]

Get cursor position (not easily available from pty).

Returns:

None (not implemented for pty)

get_echo_enabled() → bool[source]

Get echo state (not available).

get_events() → List[TerminalEvent][source]

Get event history (not available).

get_raw_mode() → bool[source]

Get raw mode state (not available).

get_screen() → List[List[str]][source]

Get screen buffer (not available).

get_screen_char(x: int, y: int) → str[source]

Get character at position (not available for PTYConsole).

Parameters:
  • x – Column (0-based)

  • y – Row (0-based)

Returns:

Space character as placeholder

get_screen_line(y: int) → str[source]

Get specific line from screen (not available for PTYConsole).

Parameters:

y – Line number (0-based)

Returns:

Empty string as placeholder

get_size() → Tuple[int, int][source]

Get pty size.

Returns:

Tuple of (columns, rows)

get_style() → Dict[str, bool][source]

Get text style state (not available for PTYConsole).

Returns:

Dictionary with all styles False

hide_cursor() → None[source]

Hide the cursor.

is_tty() → bool[source]

Check if pty is a terminal (always True).

Returns:

True (pty always behaves as TTY)

move_cursor(x: int, y: int) → None[source]

Move cursor to position.

move_cursor_down(n: int = 1) → None[source]

Move cursor down n lines.

move_cursor_home() → None[source]

Move cursor to home position.

move_cursor_left(n: int = 1) → None[source]

Move cursor left n columns.

move_cursor_right(n: int = 1) → None[source]

Move cursor right n columns.

move_cursor_up(n: int = 1) → None[source]

Move cursor up n lines.

read_char(timeout: float | None = None) → str | None[source]

Read a single character.

Parameters:

timeout – Optional timeout in seconds (not fully implemented for PTY)

Returns:

Character string or None if no input available

read_line(prompt: str = '') → str[source]

Read a line of input.

Parameters:

prompt – Optional prompt string to display

Returns:

Line of text (without newline)

read_password(prompt: str = '') → str[source]

Read password (basic implementation).

reset_color() → None[source]

Reset colors to default.

restore_cursor() → None[source]

Restore saved cursor position.

save_cursor() → None[source]

Save current cursor position.

set_color(fg: int | None = None, bg: int | None = None) → None[source]

Set foreground and/or background color.

set_echo(enabled: bool) → None[source]

Turn echo on/off (not implemented for pty).

set_raw_mode(enabled: bool) → None[source]

Enable/disable raw mode (not implemented for pty).

show_cursor() → None[source]

Show the cursor.

underline(enabled: bool = True) → None[source]

Enable or disable underline.

writable() → bool[source]

Check if pty is writable.

Returns:

True (pty is always writable)

write(s: str) → int[source]

Write string to pty.

Parameters:

s – String to write

Returns:

Number of characters written

class pyiv.PackageVersionSource(distribution: str)[source]

Bases: object

Read an installed distribution version via importlib.metadata.

Why this exists: for_package_version, for_package_present, and for_package_absent need the distribution name (as on PyPI), which is not always the import package name. This source never imports the library — it only consults packaging metadata. None means absent and is what for_package_absent matches on.

Example

>>> from pyiv.version import PackageVersionSource
>>> # ``pyiv`` itself is installed in the test / docs environment
>>> ver = PackageVersionSource("pyiv").get_version()
>>> ver is None or len(ver.split(".")) >= 2
True
>>> PackageVersionSource("pyiv-definitely-not-installed-xyz").get_version() is None
True
__init__(distribution: str) → None[source]
Parameters:

distribution – Distribution name (importlib.metadata name).

get_version() → str | None[source]

Return the installed version, or None if the dist is absent.

class pyiv.Pep440VersionParser[source]

Bases: object

VersionParser implementation for PEP 440.

Why this exists: Python package and interpreter domains need a named, standards-based parser. Config registers this under pyiv.version.PEP440 by default so for_package_version / for_python_version work without extra setup. Presence / absence (for_package_present / for_package_absent) do not use this parser — they short-circuit on PACKAGE_PRESENT / PACKAGE_ABSENT.

Example

>>> from pyiv.pep440 import Pep440VersionParser
>>> p = Pep440VersionParser()
>>> p.is_version_compatible("3.11.5", ">=3.11,<3.12")
True
>>> p.is_version_less("3.10", "3.11")
True
>>> p.is_version_greater("2.0", "1.0")
True
is_version_compatible(version: str, specifier: str) → bool[source]

Return whether version satisfies the PEP 440 specifier.

Raises:

InvalidVersion – If version or specifier is not PEP 440.

is_version_greater(a: str, b: str) → bool[source]

Return whether PEP 440 version a is strictly greater than b.

Raises:

InvalidVersion – If either string is not a PEP 440 version.

is_version_less(a: str, b: str) → bool[source]

Return whether PEP 440 version a is strictly less than b.

Raises:

InvalidVersion – If either string is not a PEP 440 version.

class pyiv.PickleSerDe[source]

Bases: SerDe

Python pickle SerDe.

Use this when you need to round-trip arbitrary Python objects that JSON, XML, or base64 text cannot represent. Prefer safer text codecs for untrusted input; pickle is a stdlib fallback for trusted local data.

Example

>>> from pyiv.serde.encodings import PickleSerDe
>>> serde = PickleSerDe()
>>> serde.handler_type
'pickle'
>>> serde.deserialize(serde.serialize({"x": 2}))
{'x': 2}
deserialize(data: str | bytes, target_type: Type[T] | None = None) → T[source]

Deserialize using pickle.

Parameters:
  • data – The pickled data (bytes)

  • target_type – Optional type hint (ignored, pickle handles types)

Returns:

Deserialized Python object

property handler_type: str

Return the handler type identifier.

Returns:

The handler type identifier (“pickle”)

serialize(obj: Any) → bytes[source]

Serialize using pickle.

Parameters:

obj – The Python object to serialize

Returns:

Pickled bytes representation

class pyiv.PrivateConfig[source]

Bases: Config

Config whose bindings are hidden unless explicitly exposed.

Why this exists: Hide internal bindings and expose only a facade type to the parent graph.

When installed into a parent config, a child injector owns the private graph. Only types/keys passed to expose() are visible to the parent (as providers that delegate into the child).

Example

>>> from pyiv import Config, PrivateConfig, get_injector
>>> class Hidden:
...     pass
>>> class Service:
...     def __init__(self, hidden: Hidden):
...         self.hidden = hidden
>>> class Impl(PrivateConfig):
...     def configure(self):
...         self.register(Hidden, Hidden)
...         self.register(Service, Service)
...         self.expose(Service)
>>> class App(Config):
...     def configure(self):
...         self.install(Impl)
>>> svc = get_injector(App).inject(Service)
>>> isinstance(svc.hidden, Hidden)
True
expose(type_or_key: Type | Key[Any]) → None[source]

Expose a binding to the parent environment when this module is installed.

class pyiv.ProcessRunner[source]

Bases: ABC

Injectable subprocess runner.

Why this exists: Call sites that use subprocess.run are hard to unit-test. Inject ProcessRunner and bind MemoryProcessRunner.

Example

>>> from pyiv.process import MemoryProcessRunner
>>> runner: ProcessRunner = MemoryProcessRunner()
>>> runner.script(["true"], returncode=0)
>>> runner.run(["true"]).returncode
0
abstract run(argv: Sequence[str], *, options: RunOptions | None = None) → CompletedProcess[source]

Run argv and return a completed process result.

class pyiv.Provider(*args, **kwargs)[source]

Bases: Protocol, Generic[T]

Protocol for provider implementations.

Why this exists: Lazy or repeated creation of a type without constructing it at inject() time; inject Provider[T] instead of T.

Providers are used to supply instances of a specific type, allowing for customized creation logic, lazy initialization, and injector access.

This is the standard pattern in dependency injection frameworks for providing instances. Providers can be injected themselves, allowing for lazy initialization and multiple instance creation.

Example

>>> from pyiv.provider import Provider
>>> from pyiv import Config, Injector, get_injector
>>>
>>> class Database:
...     pass
>>>
>>> class DatabaseProvider:
...     def __init__(self, injector: Injector):
...         self._injector = injector
...
...     def get(self) -> Database:
...         return self._injector.inject(Database)
>>>
>>> class MyConfig(Config):
...     def configure(self):
...         self.register(Database, Database)
>>>
>>> injector = get_injector(MyConfig)
>>> provider: Provider[Database] = DatabaseProvider(injector)
>>> isinstance(provider.get(), Database)
True
__init__(*args, **kwargs)
get() → T[source]

Get an instance of type T.

Returns:

An instance of type T

class pyiv.PythonDateTimeService[source]

Bases: DateTimeService

DateTime service backed by the system clock.

Use this in production for real UTC timestamps. In tests, swap in MockDateTimeService so assertions do not depend on wall-clock time.

Why this exists: Production DateTimeService backed by the system clock.

Example

>>> from datetime import datetime, timezone
>>> from pyiv.datetime_service import PythonDateTimeService
>>> svc = PythonDateTimeService()
>>> now = svc.now_utc()
>>> isinstance(now, datetime) and now.tzinfo == timezone.utc
True
>>> "T" in svc.now_utc_iso()
True
now_utc() → datetime[source]

Get current UTC datetime from system clock using Python’s datetime.

Returns:

Current datetime in UTC timezone

now_utc_iso() → str[source]

Get current UTC datetime as ISO format string using Python’s datetime.

Returns:

Current datetime in UTC as ISO format string

class pyiv.PythonVersionProvider[source]

Bases: ABC

Injectable source of the running (or simulated) Python version.

Why this exists: for_python_version and application code that branches on the interpreter must not hard-code sys.version_info. Bind SysPythonVersionProvider in production and FixedPythonVersionProvider in tests so the same graph can be exercised under 3.8, 3.10, 3.11, etc.

Example

>>> from pyiv import Config, get_injector
>>> from pyiv.version import FixedPythonVersionProvider, PythonVersionProvider
>>> class C(Config):
...     def configure(self):
...         self.get_binder().bind(PythonVersionProvider).to_instance(
...             FixedPythonVersionProvider("3.11.0")
...         )
>>> get_injector(C).inject(PythonVersionProvider).get_version()
'3.11.0'
abstract get_version() → str[source]

Return the interpreter version as a PEP 440 string (e.g. 3.11.5).

class pyiv.PythonVersionSource(provider: PythonVersionProvider | None = None, *, config: 'Config' | None = None)[source]

Bases: object

VersionSource that delegates to a PythonVersionProvider.

Why this exists: for_python_version registers this as the python domain source. At selection time it resolves (in order): an explicit constructor provider, a PythonVersionProvider bound on the config, then SysPythonVersionProvider.

Example

>>> from pyiv.version import FixedPythonVersionProvider, PythonVersionSource
>>> PythonVersionSource(FixedPythonVersionProvider("3.9.0")).get_version()
'3.9.0'
__init__(provider: PythonVersionProvider | None = None, *, config: 'Config' | None = None) → None[source]
Parameters:
  • provider – Explicit provider (wins over config bindings).

  • config – Config used to look up a bound PythonVersionProvider.

attach_config(config: Config) → None[source]

Point this source at the (possibly merged) config used for selection.

install / override may replace a submodule’s PythonVersionSource whose config= still references that submodule. Selection rebinds sources to the final merged config.

get_version() → str | None[source]

Return the resolved provider’s version string.

class pyiv.Qualifier(*args, **kwargs)[source]

Bases: Protocol

Marker for distinguishing multiple bindings of the same type.

Why this exists: One interface often has several implementations (primary vs replica DB). A qualifier + Key selects which binding to inject without inventing wrapper types.

Example

>>> from pyiv.key import Named
>>> isinstance(Named("primary"), Named)
True
__init__(*args, **kwargs)
class pyiv.RealClock[source]

Bases: Clock

Real clock implementation using standard library.

Why this exists: Production binding for real wall-clock time and sleeping timers.

This is the production implementation that uses Python’s built-in time and threading modules to provide actual system clock time and real sleep operations.

Example

>>> clock = RealClock()
>>> isinstance(clock.time(), float)
True
>>> clock.monotonic() > 0
True
monotonic() → float[source]

Get monotonic time (not affected by system clock adjustments).

Returns:

Monotonic time as float (seconds since an arbitrary point)

sleep(seconds: float) → None[source]

Sleep for specified duration.

Parameters:

seconds – Duration to sleep in seconds

start_timer(interval: float, callback: Callable[[], None], repeat: bool = False) → Timer[source]

Start a timer using threading.Timer.

Parameters:
  • interval – Time interval in seconds before callback is called

  • callback – Function to call when timer fires

  • repeat – If True, timer will repeat after each interval

Returns:

Timer object that can be used to cancel the timer

thread_sleep(seconds: float) → None[source]

Sleep in current thread.

Parameters:

seconds – Duration to sleep in seconds

time() → float[source]

Get current time as seconds since epoch.

Returns:

Current time as float (seconds since Unix epoch)

class pyiv.RealConsole(stream: TextIO | None = None, stdin: TextIO | None = None)[source]

Bases: BaseConsole

Production console implementation using sys.stdout.

This console wraps sys.stdout, providing the standard console output behavior and TTY-specific functionality. Use this in production code for normal console output and terminal features like spinners, animations, and password prompts.

Why this exists: Production Console that writes to a real stream/TTY.

Example

>>> from io import StringIO
>>> from pyiv.console import RealConsole
>>>
>>> buf = StringIO()
>>> console = RealConsole(stream=buf)
>>> print("Hello, World!", file=console)
>>> "Hello, World!" in buf.getvalue()
True
__init__(stream: TextIO | None = None, stdin: TextIO | None = None)[source]

Initialize console with streams.

Parameters:
  • stream – TextIO stream to use for output (defaults to sys.stdout)

  • stdin – TextIO stream to use for input (defaults to sys.stdin)

bold(enabled: bool = True) → None[source]

Enable or disable bold text.

Parameters:

enabled – True to enable bold, False to disable

clear() → None[source]

Clear the entire screen.

clear_line() → None[source]

Clear the current line.

clear_state() → None[source]

Clear all state (no-op for RealConsole).

clear_to_end_of_line() → None[source]

Clear from cursor to end of line.

flush() → None[source]

Flush stdout buffer.

get_color() → Tuple[int | None, int | None][source]

Get current color state (not available for RealConsole).

Returns:

Tuple of (None, None) as placeholder

get_cursor() → Tuple[int, int][source]

Get current cursor position (not available for RealConsole).

Returns:

Tuple of (0, 0) as placeholder

get_cursor_position() → Tuple[int, int] | None[source]

Get current cursor position.

Note: This requires reading a response from the terminal, which may not be available in all contexts.

Returns:

Tuple of (x, y) or None if not available

get_echo_enabled() → bool[source]

Get echo state (not available for RealConsole).

Returns:

True as placeholder

get_events() → List[TerminalEvent][source]

Get event history (not available for RealConsole).

Returns:

Empty list as placeholder

get_raw_mode() → bool[source]

Get raw mode state (not available for RealConsole).

Returns:

False as placeholder

get_screen() → List[List[str]][source]

Get screen buffer (not available for RealConsole).

Returns:

Empty list as placeholder

get_screen_char(x: int, y: int) → str[source]

Get character at position (not available for RealConsole).

Parameters:
  • x – Column (0-based)

  • y – Row (0-based)

Returns:

Space character as placeholder

get_screen_line(y: int) → str[source]

Get specific line from screen (not available for RealConsole).

Parameters:

y – Line number (0-based)

Returns:

Empty string as placeholder

get_size() → Tuple[int, int][source]

Get terminal size.

Returns:

Tuple of (columns, rows)

get_style() → Dict[str, bool][source]

Get text style state (not available for RealConsole).

Returns:

Dictionary with all styles False

hide_cursor() → None[source]

Hide the cursor.

is_tty() → bool[source]

Check if stdout is a real terminal.

Returns:

True if stdout is connected to a TTY

move_cursor(x: int, y: int) → None[source]

Move cursor to position.

Parameters:
  • x – Column (0-based, but ANSI uses 1-based)

  • y – Row (0-based, but ANSI uses 1-based)

move_cursor_down(n: int = 1) → None[source]

Move cursor down n lines.

move_cursor_home() → None[source]

Move cursor to home position (0, 0).

move_cursor_left(n: int = 1) → None[source]

Move cursor left n columns.

move_cursor_right(n: int = 1) → None[source]

Move cursor right n columns.

move_cursor_up(n: int = 1) → None[source]

Move cursor up n lines.

read_char(timeout: float | None = None) → str | None[source]

Read a single character (requires raw mode).

Parameters:

timeout – Optional timeout in seconds

Returns:

Character string or None if no input available

read_line(prompt: str = '') → str[source]

Read a line of input.

Parameters:

prompt – Optional prompt string to display

Returns:

Line of text (without newline)

read_password(prompt: str = '') → str[source]

Read password with echo disabled.

Parameters:

prompt – Optional prompt to display

Returns:

Password string

reset_color() → None[source]

Reset colors to default.

restore_cursor() → None[source]

Restore saved cursor position.

save_cursor() → None[source]

Save current cursor position.

set_color(fg: int | None = None, bg: int | None = None) → None[source]

Set foreground and/or background color.

Parameters:
  • fg – Foreground color code (30-37 for basic, 90-97 for bright)

  • bg – Background color code (40-47 for basic, 100-107 for bright)

set_echo(enabled: bool) → None[source]

Turn echo on/off for password prompts.

Parameters:

enabled – True to enable echo, False to disable

set_raw_mode(enabled: bool) → None[source]

Enable/disable raw mode for character-by-character input.

Parameters:

enabled – True for raw mode, False for cooked mode

show_cursor() → None[source]

Show the cursor.

underline(enabled: bool = True) → None[source]

Enable or disable underline.

Parameters:

enabled – True to enable underline, False to disable

writable() → bool[source]

Check if stdout is writable.

Returns:

True if stdout is writable

write(s: str) → int[source]

Write string to stdout.

Parameters:

s – String to write

Returns:

Number of characters written

class pyiv.RealEntropy[source]

Bases: Entropy

Entropy backed by secrets / random.

Why this exists: Production cryptographic-ish tokens via stdlib.

choice(seq: Sequence[T]) → T[source]

Choose one element from seq.

randbytes(n: int) → bytes[source]

Return n random bytes.

token_urlsafe(nbytes: int = 32) → str[source]

Return a URL-safe token.

class pyiv.RealFilesystem(root: str | Path | None = None)[source]

Bases: Filesystem

Real filesystem implementation using the standard library.

Use this in production when you need actual disk I/O. Prefer MemoryFilesystem in unit tests so examples and CI never write into the working tree. Optional root= chroots all paths under a sandbox.

Why this exists: Production Filesystem that performs real disk I/O.

Example

>>> import tempfile
>>> from pathlib import Path
>>> from pyiv.files import RealFilesystem
>>> fs = RealFilesystem()
>>> with tempfile.TemporaryDirectory() as d:
...     p = Path(d) / "hello.txt"
...     fs.write_text(p, "hi")
...     fs.read_text(p)
'hi'
__init__(root: str | Path | None = None) → None[source]
copy(src: str | Path, dst: str | Path) → None[source]

Copy a file.

Parameters:
  • src – Source file path

  • dst – Destination file path

exists(path: str | Path) → bool[source]

Check if path exists.

Parameters:

path – Path to check

Returns:

True if path exists, False otherwise

get_size(path: str | Path) → int[source]

Get file size in bytes.

Parameters:

path – File path

Returns:

File size in bytes

glob(pattern: str | Path) → Iterator[Path][source]

Glob pattern matching.

Parameters:

pattern – Glob pattern to match

Yields:

Matching paths

is_dir(path: str | Path) → bool[source]

Check if path is a directory.

Parameters:

path – Path to check

Returns:

True if path is a directory, False otherwise

is_file(path: str | Path) → bool[source]

Check if path is a file.

Parameters:

path – Path to check

Returns:

True if path is a file, False otherwise

listdir(path: str | Path) → Iterator[str][source]

List directory contents.

Parameters:

path – Directory path to list

Yields:

Directory entry names

mkdir(path: str | Path, parents: bool = False, exist_ok: bool = False) → None[source]

Create a directory.

Parameters:
  • path – Directory path to create

  • parents – Create parent directories if needed

  • exist_ok – Don’t raise error if directory already exists

move(src: str | Path, dst: str | Path) → None[source]

Move/rename a file or directory.

Parameters:
  • src – Source path

  • dst – Destination path

open(file: str | Path, mode: str = 'r', encoding: str | None = None) → TextIO | BinaryIO[source]

Open a file using built-in open().

Parameters:
  • file – File path to open

  • mode – File mode (r, w, a, rb, wb, etc.)

  • encoding – Text encoding (for text modes, ignored for binary modes)

Returns:

File handle (TextIO for text modes, BinaryIO for binary modes)

read_bytes(path: str | Path) → bytes[source]

Read bytes from a file.

Parameters:

path – File path to read

Returns:

File contents as bytes

read_text(path: str | Path, encoding: str = 'utf-8') → str[source]

Read text from a file.

Parameters:
  • path – File path to read

  • encoding – Text encoding (default: utf-8)

Returns:

File contents as string

rmdir(path: str | Path) → None[source]

Remove a directory.

Parameters:

path – Directory path to remove (must be empty)

Remove a file.

Parameters:
  • path – File path to remove

  • missing_ok – Don’t raise error if file doesn’t exist

write_bytes(path: str | Path, content: bytes) → None[source]

Write bytes to a file.

Parameters:
  • path – File path to write

  • content – Bytes content to write

write_text(path: str | Path, content: str, encoding: str = 'utf-8') → None[source]

Write text to a file.

Parameters:
  • path – File path to write

  • content – Text content to write

  • encoding – Text encoding (default: utf-8)

class pyiv.RealHasher[source]

Bases: Hasher

Hasher backed by hashlib / hmac.

Why this exists: Production digests via the standard library.

digest(algorithm: str, data: bytes) → bytes[source]

Return a digest of data using algorithm.

hmac_digest(algorithm: str, key: bytes, data: bytes) → bytes[source]

Return HMAC of data with key.

class pyiv.RealProcessRunner[source]

Bases: ProcessRunner

Process runner backed by subprocess.run.

Why this exists: Production binding for real child processes.

run(argv: Sequence[str], *, options: RunOptions | None = None) → CompletedProcess[source]

Run argv and return a completed process result.

class pyiv.ReflectionConfig[source]

Bases: Config

Configuration that discovers implementations in packages via reflection.

Why this exists: Auto-discover interface implementations in a package instead of listing every class. Use as_multibind when discoveries must accumulate into a catalog (map/set/list) rather than overwrite a single unqualified binding.

Example

>>> import sys, types
>>> from pyiv import get_injector
>>> from pyiv.reflection import ReflectionConfig
>>> class Tool:
...     name = "base"
>>> pkg = types.ModuleType("doctest_tools_pkg")
>>> class GrepTool(Tool):
...     name = "grep"
>>> class LintTool(Tool):
...     name = "lint"
>>> GrepTool.__module__ = "doctest_tools_pkg"
>>> LintTool.__module__ = "doctest_tools_pkg"
>>> pkg.GrepTool = GrepTool
>>> pkg.LintTool = LintTool
>>> sys.modules["doctest_tools_pkg"] = pkg
>>> class ToolConfig(ReflectionConfig):
...     def configure(self):
...         self.register_module(
...             Tool,
...             "doctest_tools_pkg",
...             pattern="*Tool",
...             as_multibind="map",
...             key_attr="name",
...             recursive=False,
...         )
>>> get_injector(ToolConfig).catalog_keys(Tool)
['grep', 'lint']
__init__()[source]

Initialize the reflection configuration.

_module_registrations must exist before Config.__init__ runs configure(), which may call register_module().

discover_implementations(interface: Type) → Dict[str, Type][source]

Discover all implementations of an interface in registered modules.

This method scans the registered package for classes that implement the given interface. Only classes within the specified package (and optionally submodules) are discovered - no discovery happens outside the registered package boundaries.

Parameters:

interface – The interface to discover implementations for

Returns:

Dictionary mapping implementation names to classes. Keys are class names (or “submodule.ClassName” for submodules).

Raises:
  • ValueError – If no module registration exists for the interface

  • ImportError – If the package cannot be imported

register_module(interface: Type, package_path: str, pattern: str | None = None, recursive: bool = True, singleton_type: SingletonType = SingletonType.SINGLETON, *, as_multibind: Literal['map', 'set', 'list'] | None = None, key_attr: str | None = None, on_conflict: Literal['replace', 'error', 'keep'] = 'error')[source]

Register a package to scan for interface implementations.

Parameters:
  • interface – The abstract class or interface to find implementations of

  • package_path – Python package path (e.g., “my_service.mcp.handlers”)

  • pattern – Optional name pattern for filtering (e.g. *Handler, handle_*). Uses fnmatch syntax. If None, all implementations are discovered.

  • recursive – Whether to scan submodules recursively (default: True)

  • singleton_type – How to handle instances on the legacy unqualified register path (ignored when as_multibind is set)

  • as_multibind – If None (default), each discovery calls register(interface, impl) (last wins). If "map", "set", or "list", discoveries join that multibind only and do not overwrite the unqualified binding.

  • key_attr – Class attribute name used as the map key when as_multibind="map" (required in that mode)

  • on_conflict – Conflict policy for map multibind contributions (default "error" so duplicate catalog ids fail loudly)

Raises:
  • TypeError – If interface is not a type

  • ImportError – If the package cannot be imported

  • ValueError – If map mode lacks key_attr or a class lacks the attr

Example

>>> import sys, types
>>> from pyiv.reflection import ReflectionConfig
>>> class Handler:
...     pass
>>> pkg = types.ModuleType("doctest_handler_list")
>>> class CreateHandler(Handler):
...     pass
>>> class UpdateHandler(Handler):
...     pass
>>> CreateHandler.__module__ = "doctest_handler_list"
>>> UpdateHandler.__module__ = "doctest_handler_list"
>>> pkg.CreateHandler = CreateHandler
>>> pkg.UpdateHandler = UpdateHandler
>>> sys.modules["doctest_handler_list"] = pkg
>>> class ListConfig(ReflectionConfig):
...     def configure(self):
...         self.register_module(
...             Handler,
...             "doctest_handler_list",
...             pattern="*Handler",
...             as_multibind="list",
...             recursive=False,
...         )
>>> mb = ListConfig().get_multibinding(Handler)
>>> sorted(c.__name__ for c in mb[1])
['CreateHandler', 'UpdateHandler']
class pyiv.RunOptions(cwd: str | None = None, env: Mapping[str, str] | None = None, timeout: float | None = None, check: bool = False, text: bool = True)[source]

Bases: object

Options for a single ProcessRunner.run call.

Why this exists: Frozen knob for Settings nesting without pydantic.

Example

>>> RunOptions(timeout=1.0).as_dict()["timeout"]
1.0
__init__(cwd: str | None = None, env: Mapping[str, str] | None = None, timeout: float | None = None, check: bool = False, text: bool = True) → None
as_dict() → Dict[str, Any][source]
check: bool = False
cwd: str | None = None
env: Mapping[str, str] | None = None
text: bool = True
timeout: float | None = None
class pyiv.Scope(*args, **kwargs)[source]

Bases: Protocol

Protocol for scope implementations.

Why this exists: Control instance lifetime beyond one-shot construction (request, singleton, custom).

Scopes control the lifecycle of instances created by the dependency injection system. A scope can cache instances, create new ones on demand, or implement custom lifecycle logic.

Scopes are more flexible than simple singletons - they can implement request-scoped, thread-scoped, session-scoped, or any custom lifecycle.

Example:

class RequestScope(Scope):
    def __init__(self):
        self._request_cache = {}

    def scope(self, key, provider):
        request_id = get_current_request_id()
        cache_key = (key, request_id)
        if cache_key not in self._request_cache:
            self._request_cache[cache_key] = provider.get()
        return lambda: self._request_cache[cache_key]
__init__(*args, **kwargs)
scope(key: Type | str | tuple, provider: Provider[Any]) → Provider[Any][source]

Scope a provider to this scope’s lifecycle.

Parameters:
  • key – The key identifying the dependency (Type, str, or tuple)

  • provider – The provider to scope

Returns:

A new provider that respects this scope’s lifecycle

class pyiv.SerDe[source]

Bases: ChainHandler

Abstract base class for serialization/deserialization operations.

SerDe is a chain handler for the ENCODING chain. Subclass it for each codec (JSON, base64, XML, pickle, etc.); YAML lives in pyiv-common.

Use this when callers should pick a codec by handler_type instead of hard-coding json.dumps / pickle.loads. Register implementations on the ENCODING chain so injectors and pipelines can swap formats without rewriting call sites. Multiple handlers may share a handler_type with different behaviors (date formatting, null handling, and so on).

Subclasses must implement handler_type, serialize, and deserialize.

Example

>>> import json
>>> from typing import Any, Optional, Type
>>> from pyiv.serde.base import SerDe
>>> class MyJSONSerDe(SerDe):
...     @property
...     def handler_type(self) -> str:
...         return "json"
...     def serialize(self, obj: Any) -> str:
...         return json.dumps(obj)
...     def deserialize(
...         self, data: str, target_type: Optional[Type] = None
...     ) -> Any:
...         return json.loads(data)
>>> serde = MyJSONSerDe()
>>> serde.deserialize(serde.serialize({"a": 1}))
{'a': 1}
property chain_type: ChainType

Return the chain type (always ENCODING for SerDe).

Returns:

ChainType.ENCODING

abstract deserialize(data: str | bytes, target_type: Type[T] | None = None) → T[source]

Deserialize encoded data back to a Python object.

Parameters:
  • data – The encoded data (string or bytes)

  • target_type – Optional type hint for the expected result type

Returns:

Deserialized Python object

handle(request: Any, **kwargs) → Any[source]

Handle a serialization/deserialization request.

This is the chain handler interface. For SerDe, requests can be: - A tuple of (“serialize”, obj) -> returns serialized data - A tuple of (“deserialize”, data, target_type) -> returns deserialized object - A dict with “action” key -> processes accordingly

Parameters:
  • request – The request (can be tuple, dict, or direct object)

  • **kwargs – Additional keyword arguments

Returns:

The result of the operation

abstract property handler_type: str

Return the encoding type identifier (e.g., “json”, “base64”, “pickle”).

Returns:

A string identifying the encoding format

abstract serialize(obj: Any) → str | bytes[source]

Serialize a Python object to encoded format.

Parameters:

obj – The Python object to serialize

Returns:

Serialized representation as string or bytes

class pyiv.ServiceCommand(args: Namespace, injector: Any | None = None)[source]

Bases: Command

Base class for long-running service commands.

Use this when a command should run until interrupted (daemons, workers). execute() runs init() → run() → cleanup() and maps KeyboardInterrupt to exit code 130. Override those hooks; do not reimplement the lifecycle unless necessary.

Example

>>> import argparse
>>> from pyiv.command import ServiceCommand
>>> class OnceService(ServiceCommand):
...     @classmethod
...     def get_name(cls) -> str:
...         return "once"
...     def run(self) -> None:
...         pass  # exit immediately after init
>>> OnceService(argparse.Namespace()).execute()
0
execute() → int[source]

Execute the service command lifecycle.

Returns:

Exit code (0 for success, non-zero for error)

class pyiv.SetMultibinder(interface: Type[T], config: Any)[source]

Bases: Generic[T]

Multibinder that binds to a Set[T].

Why this exists: Collect unique implementations as Set[T] (order not preserved).

This multibinder collects implementations into a set, ensuring uniqueness. Order is not preserved.

Example

>>> from pyiv import Config
>>> class EventHandler:
...     pass
>>> class EmailEventHandler(EventHandler):
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         pass
>>> multibinder = SetMultibinder(EventHandler, MyConfig())
>>> multibinder.add(EmailEventHandler)
>>> EmailEventHandler in multibinder.get_implementations()
True
__init__(interface: Type[T], config: Any)[source]

Initialize set multibinder.

Parameters:
  • interface – The interface type

  • config – The config to register bindings with

add(implementation: Type[T]) → None[source]

Add an implementation class.

Parameters:

implementation – The implementation class to add

add_instance(instance: T) → None[source]

Add a pre-created instance.

Parameters:

instance – The instance to add

get_implementations() → Set[Type[T]][source]

Get all registered implementation classes.

Returns:

Set of implementation classes

get_instances() → Set[T][source]

Get all registered instances.

Returns:

Set of instances

class pyiv.SimpleFactory(callable_factory: Callable[[...], T])[source]

Bases: Generic[T]

Simple factory that wraps a callable.

Why this exists: Wrap a function/constructor as a Factory without defining a subclass.

Useful for creating factories from functions or constructors without needing to define a full class.

Example

>>> class User:
...     def __init__(self, name: str):
...         self.name = name
>>> def create_user(name: str) -> User:
...     return User(name=name)
>>> from pyiv.factory import SimpleFactory
>>> factory = SimpleFactory(create_user)
>>> factory.create("Alice").name
'Alice'
__init__(callable_factory: Callable[[...], T])[source]

Initialize factory with a callable.

Parameters:

callable_factory – A callable (function, class, etc.) that creates instances

create(*args: Any, **kwargs: Any) → T[source]

Create an instance using the wrapped callable.

Parameters:
  • *args – Positional arguments passed to the callable

  • **kwargs – Keyword arguments passed to the callable

Returns:

An instance created by the callable

class pyiv.SingletonScope[source]

Bases: object

Per-injector singleton scope.

Why this exists: One instance per injector — default app-wide singleton without process globals.

This scope caches instances per injector. Each injector will have its own singleton instance. This is useful when you want singletons but need different instances for different injectors (e.g., test vs production).

Example

>>> from pyiv.scope import SingletonScope
>>> from pyiv import Config
>>>
>>> class MyConfig(Config):
...     def configure(self):
...         # Per-injector singleton
...         self.register(Logger, FileLogger, scope=SingletonScope())
__init__()[source]

Initialize the singleton scope.

scope(key: Type | str | tuple, provider: Provider[Any]) → Provider[Any][source]

Scope provider to per-injector singleton.

Parameters:
  • key – The key identifying the dependency

  • provider – The provider to scope

Returns:

A provider that returns the same instance for this scope

class pyiv.SingletonType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Legacy enum for singleton lifecycle on Config.register.

Why this exists: Older call sites use singleton_type=... instead of a Scope. Prefer Scope for new code; this enum remains for compatibility.

NONE

No singleton behavior - new instance created each time

SINGLETON

Per-injector singleton - one instance per Injector instance

GLOBAL_SINGLETON

Global singleton - one instance shared across all injectors (thread-safe)

Example

>>> from pyiv import Config, get_injector
>>> class Logger:
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         self.register(Logger, Logger, singleton_type=SingletonType.SINGLETON)
>>> inj = get_injector(MyConfig)
>>> inj.inject(Logger) is inj.inject(Logger)
True
GLOBAL_SINGLETON = 'global_singleton'
NONE = 'none'
SINGLETON = 'singleton'
class pyiv.Stage(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Injector construction stage: lazy vs fail-fast singletons.

Why this exists: Lazy singletons hide binding mistakes until first use. Pass stage=Stage.PRODUCTION to get_injector() so singleton-scoped bindings are created at boot.

DEVELOPMENT

Singletons are created lazily on first inject (default).

PRODUCTION

Singleton-scoped bindings are created when the injector is built.

Example

>>> from pyiv import Config, Stage, get_injector
>>> from pyiv.scope import SingletonScope
>>> class Database:
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         self.get_binder().bind(Database).to(Database).in_scope(SingletonScope())
>>> isinstance(get_injector(MyConfig, stage=Stage.PRODUCTION).inject(Database), Database)
True
DEVELOPMENT = 'development'
PRODUCTION = 'production'
class pyiv.StdlibLogger(logger: Logger)[source]

Bases: Logger

Logger wrapping a stdlib logging.Logger.

Why this exists: Production emit path that still participates in the stdlib hierarchy (third-party libs keep working).

__init__(logger: Logger) → None[source]
debug(msg: str, *args: Any, **kwargs: Any) → None[source]

Log a debug message.

error(msg: str, *args: Any, **kwargs: Any) → None[source]

Log an error message.

exception(msg: str, *args: Any, **kwargs: Any) → None[source]

Log an error with exception info.

info(msg: str, *args: Any, **kwargs: Any) → None[source]

Log an info message.

log(level: int, msg: str, *args: Any, **kwargs: Any) → None[source]

Log at a numeric level (default routes through info for Memory).

warning(msg: str, *args: Any, **kwargs: Any) → None[source]

Log a warning message.

class pyiv.StdlibLoggerFactory[source]

Bases: LoggerFactory

Factory wrapping logging.getLogger.

Why this exists: Production factory that stays on the stdlib hierarchy.

get(name: str | Type[Any]) → Logger[source]

Return a logger for name (string or type).

class pyiv.SyntheticClock(start_time: float = 0.0)[source]

Bases: Clock

Synthetic clock for testing - allows manual time control.

This implementation allows you to control time manually, making it easy to test time-dependent code with predictable timestamps. Time advances only when you call advance() or set_time().

Why this exists: Controllable clock for tests — advance time without sleeping.

Example

>>> clock = SyntheticClock(start_time=100.0)
>>> assert clock.time() == 100.0
>>> clock.advance(5.0)
>>> assert clock.time() == 105.0
>>> clock.set_time(200.0)
>>> assert clock.time() == 200.0
__init__(start_time: float = 0.0)[source]

Initialize synthetic clock.

Parameters:

start_time – Initial time value

advance(seconds: float) → None[source]

Manually advance time.

Parameters:

seconds – Amount to advance time by

monotonic() → float[source]

Get monotonic time.

Returns:

Monotonic time value (same as time() for synthetic clock)

set_time(time_value: float) → None[source]

Set the current time.

Parameters:

time_value – Time value to set

sleep(seconds: float) → None[source]

Advance time instead of actually sleeping.

Parameters:

seconds – Amount of time to advance (does not actually sleep)

start_timer(interval: float, callback: Callable[[], None], repeat: bool = False) → SyntheticTimer[source]

Start a synthetic timer.

Parameters:
  • interval – Time interval in seconds before callback is called

  • callback – Function to call when timer fires

  • repeat – If True, timer will repeat after each interval

Returns:

SyntheticTimer object that can be used to cancel the timer

thread_sleep(seconds: float) → None[source]

Advance time instead of actually sleeping.

Parameters:

seconds – Amount of time to advance (does not actually sleep)

time() → float[source]

Get current synthetic time.

Returns:

Current synthetic time value

class pyiv.SyntheticEntropy(seed: int | None = None)[source]

Bases: Entropy

Seeded entropy for deterministic tests.

Why this exists: Replayable nonces without patching secrets.

Example

>>> a = SyntheticEntropy(seed=7)
>>> b = SyntheticEntropy(seed=7)
>>> a.token_urlsafe(8) == b.token_urlsafe(8)
True
__init__(seed: int | None = None) → None[source]
choice(seq: Sequence[T]) → T[source]

Choose one element from seq.

randbytes(n: int) → bytes[source]

Return n random bytes.

token_urlsafe(nbytes: int = 32) → str[source]

Return a URL-safe token.

class pyiv.SyntheticHasher(fixed: bytes | None = None)[source]

Bases: Hasher

Hasher that returns fixed digests (optional) for tests.

Why this exists: Assert hashing call shapes without real crypto cost.

Example

>>> h = SyntheticHasher(fixed=b"\x00\x01")
>>> h.digest("sha256", b"x")
b'\x00\x01'
__init__(fixed: bytes | None = None) → None[source]
digest(algorithm: str, data: bytes) → bytes[source]

Return a digest of data using algorithm.

hmac_digest(algorithm: str, key: bytes, data: bytes) → bytes[source]

Return HMAC of data with key.

class pyiv.SysArgv[source]

Bases: Argv

Argv backed by sys.argv / sys.exit.

Why this exists: Production binding for real CLI entrypoints.

property args: Sequence[str]

Program arguments including argv[0].

exit(code: int = 0) → None[source]

Request process exit with code.

class pyiv.SysPythonVersionProvider[source]

Bases: PythonVersionProvider

Production PythonVersionProvider backed by sys.version_info.

Why this exists: Default for for_python_version when no test provider is bound. Prefer injecting PythonVersionProvider over calling this class directly.

Example

>>> from pyiv.version import SysPythonVersionProvider
>>> from pyiv.pep440 import Pep440VersionParser
>>> ver = SysPythonVersionProvider().get_version()
>>> Pep440VersionParser().is_version_compatible(ver, ">=3.8")
True
get_version() → str[source]

Return major.minor.micro for sys.version_info.

class pyiv.TarFilesystem(source: str | Path | bytes)[source]

Bases: Filesystem

Treat a tar archive as a read-oriented Filesystem tree.

Why this exists: Same consumer API as disk/memory/zip for bundled trees.

Example

>>> import io, tarfile
>>> from pyiv.files import TarFilesystem
>>> buf = io.BytesIO()
>>> with tarfile.open(fileobj=buf, mode="w") as tf:
...     info = tarfile.TarInfo(name="a.txt")
...     data = b"x"
...     info.size = len(data)
...     tf.addfile(info, io.BytesIO(data))
>>> fs = TarFilesystem(buf.getvalue())
>>> fs.read_text("/a.txt")
'x'
__init__(source: str | Path | bytes) → None[source]
copy(src: str | Path, dst: str | Path) → None[source]

Copy a file.

Parameters:
  • src – Source path

  • dst – Destination path

exists(path: str | Path) → bool[source]

Check if a path exists.

Parameters:

path – Path to check

Returns:

True if path exists, False otherwise

get_size(path: str | Path) → int[source]

Get file size in bytes.

Parameters:

path – File path

Returns:

File size in bytes

glob(pattern: str | Path) → Iterator[Path][source]

Glob pattern matching.

Parameters:

pattern – Glob pattern

Yields:

Matching paths

is_dir(path: str | Path) → bool[source]

Check if path is a directory.

Parameters:

path – Path to check

Returns:

True if path is a directory, False otherwise

is_file(path: str | Path) → bool[source]

Check if path is a file.

Parameters:

path – Path to check

Returns:

True if path is a file, False otherwise

listdir(path: str | Path) → Iterator[str][source]

List directory contents.

Parameters:

path – Directory path

Yields:

Directory entry names

mkdir(path: str | Path, parents: bool = False, exist_ok: bool = False) → None[source]

Create a directory.

Parameters:
  • path – Directory path

  • parents – Create parent directories if needed

  • exist_ok – Don’t raise error if directory exists

move(src: str | Path, dst: str | Path) → None[source]

Move/rename a file or directory.

Parameters:
  • src – Source path

  • dst – Destination path

open(file: str | Path, mode: str = 'r', encoding: str | None = None) → TextIO | BinaryIO[source]

Open a file.

Parameters:
  • file – File path

  • mode – File mode (r, w, a, rb, wb, etc.)

  • encoding – Text encoding (for text modes)

Returns:

File handle

read_bytes(path: str | Path) → bytes[source]

Read bytes from a file.

Parameters:

path – File path

Returns:

File contents as bytes

read_text(path: str | Path, encoding: str = 'utf-8') → str[source]

Read text from a file.

Parameters:
  • path – File path

  • encoding – Text encoding

Returns:

File contents as string

rmdir(path: str | Path) → None[source]

Remove a directory.

Parameters:

path – Directory path

Remove a file.

Parameters:
  • path – File path

  • missing_ok – Don’t raise error if file doesn’t exist

write_bytes(path: str | Path, content: bytes) → None[source]

Write bytes to a file.

Parameters:
  • path – File path

  • content – Bytes content to write

write_text(path: str | Path, content: str, encoding: str = 'utf-8') → None[source]

Write text to a file.

Parameters:
  • path – File path

  • content – Text content to write

  • encoding – Text encoding

class pyiv.Timer[source]

Bases: ABC

Abstract handle for a scheduled callback.

Use timers when code needs one-shot or repeating callbacks driven by a Clock. Prefer SyntheticClock.start_timer in tests so time advances only when you call advance(), not wall-clock sleep.

Example

>>> from pyiv.clock import SyntheticClock
>>> clock = SyntheticClock(start_time=0.0)
>>> fired = []
>>> timer = clock.start_timer(5.0, lambda: fired.append(True), repeat=False)
>>> timer.is_active()
True
>>> clock.advance(5.0)
>>> fired
[True]
>>> timer.cancel()
abstract cancel() → None[source]

Cancel the timer.

Returns:

None

abstract is_active() → bool[source]

Check if timer is still active.

Returns:

True if active, False otherwise

class pyiv.UrllibHttpClient(base_url=None, headers=None, timeout=None, https_only=False, options=None)[source]

Bases: HttpClient

HTTP(S) client using stdlib urllib.

Why this exists: Core pyiv stays zero-dependency. This is the default production HttpClient when you do not want requests/httpx.

Example

>>> client = UrllibHttpClient()
>>> client.request("GET", "ftp://example.com/")
Traceback (most recent call last):
    ...
ValueError: Only http:// and https:// URLs are allowed, got: ftp://example.com/
>>> from pyiv.http.options import HttpClientOptions
>>> UrllibHttpClient(options=HttpClientOptions(https_only=True))._https_only
True
__init__(base_url=None, headers=None, timeout=None, https_only=False, options=None) → None[source]
request(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → HttpResponse[source]

Send an HTTP request and return a buffered response.

stream(method: str, url: str, *, headers: Mapping[str, str] | None = None, params: Mapping[str, Any] | None = None, data: str | bytes | None = None, json: Any = None, timeout: float | None = None) → Iterator[StreamResponse][source]

Open a streaming response (context manager).

class pyiv.VersionBindingCandidate(abstract: Type[Any], domain: str, specifier: str, implementation: Type[Any] | None = None, instance: Any = None, provider: Provider[Any] | None = None, scope: Scope | None = None, parser_name: str | None = None)[source]

Bases: object

One version-conditioned alternative for an abstract type.

Why this exists: Unconditional Config registrations are last-wins dictionaries. Version alternatives (including package presence / absence) must accumulate as candidates and be selected after config composition. Hosts rarely construct this type directly — prefer binder.bind(...).to(...).for_version(...) / for_package_present / for_package_absent.

Example

>>> from pyiv.version import PACKAGE_PRESENT, VersionBindingCandidate
>>> class HttpClient:
...     pass
>>> class LegacyClient(HttpClient):
...     pass
>>> c = VersionBindingCandidate(
...     abstract=HttpClient,
...     domain="package:requests",
...     specifier="<2.30",
...     implementation=LegacyClient,
... )
>>> c.specifier
'<2.30'
>>> VersionBindingCandidate(
...     abstract=HttpClient,
...     domain="package:cjson",
...     specifier=PACKAGE_PRESENT,
...     implementation=LegacyClient,
... ).specifier
'*'
__init__(abstract: Type[Any], domain: str, specifier: str, implementation: Type[Any] | None = None, instance: Any = None, provider: Provider[Any] | None = None, scope: Scope | None = None, parser_name: str | None = None) → None
abstract: Type[Any]
domain: str
implementation: Type[Any] | None = None
instance: Any = None
parser_name: str | None = None
provider: Provider[Any] | None = None
scope: Scope | None = None
specifier: str
class pyiv.VersionParser(*args, **kwargs)[source]

Bases: Protocol

Parses and matches version strings for a named grammar.

Why this exists: Python package and interpreter versions follow PEP 440, but hosts often condition bindings on OS releases, wire protocols, or schema epochs that do not. Implement this protocol, register it with pyiv.binder.Binder.version_parser() under a name, and point domains at that name with pyiv.binder.Binder.use_version_parser(). Raise InvalidVersion (or a subclass) on unusable input.

Example

>>> from pyiv.pep440 import Pep440VersionParser
>>> p = Pep440VersionParser()
>>> p.is_version_compatible("2.31.0", ">=2.30,<3")
True
>>> p.is_version_less("1.0", "2.0")
True
>>> p.is_version_greater("2.0", "1.0")
True
__init__(*args, **kwargs)
is_version_compatible(version: str, specifier: str) → bool[source]

Return True if version satisfies specifier for this grammar.

Raises:

InvalidVersion – If version or specifier cannot be parsed.

is_version_greater(a: str, b: str) → bool[source]

Return True if a is strictly greater than b.

Raises:

InvalidVersion – If either string cannot be parsed.

is_version_less(a: str, b: str) → bool[source]

Return True if a is strictly less than b.

Raises:

InvalidVersion – If either string cannot be parsed.

class pyiv.VersionSource(*args, **kwargs)[source]

Bases: Protocol

Provides the current version string for a named domain.

Why this exists: Selection must read environment state (installed distribution, interpreter, host OS) without baking discovery into the binder. Implement this for custom domains, or use MapVersionSource in tests.

Example

>>> from pyiv.version import MapVersionSource
>>> src = MapVersionSource({"alpine": "3.19.0"})
>>> src.get_version()
'3.19.0'
__init__(*args, **kwargs)
get_version() → str | None[source]

Return the current version, or None if absent / unknown.

class pyiv.XMLSerDe[source]

Bases: SerDe

XML encoding SerDe for simple dict/list structures.

Use this when interoperability with XML-oriented systems matters and the payload is a shallow dict or list. Nested dicts become child elements; lists become item children. Not a full schema or namespace mapper.

Example

>>> from pyiv.serde.encodings import XMLSerDe
>>> serde = XMLSerDe()
>>> serde.handler_type
'xml'
>>> xml = serde.serialize({"name": "Ada"})
>>> xml
'<root><name>Ada</name></root>'
>>> serde.deserialize(xml)
{'name': 'Ada'}
deserialize(data: str | bytes, target_type: Type[T] | None = None) → T[source]

Deserialize XML string/bytes back to a Python object.

Parameters:
  • data – The XML string or bytes

  • target_type – Optional type hint (returns dict by default)

Returns:

Deserialized Python object (dict or list)

property handler_type: str

Return the handler type identifier.

Returns:

The handler type identifier (“xml”)

serialize(obj: Any) → str[source]

Serialize using XML encoding.

Parameters:

obj – The Python object to serialize (dict or list)

Returns:

XML string representation

class pyiv.ZipFilesystem(source: str | Path | bytes, *, mode: Literal['r', 'w', 'x', 'a'] = 'r')[source]

Bases: Filesystem

Treat a ZIP archive as a Filesystem tree (read; write when writable).

Why this exists: Apps that read config or assets from a zip should inject the same Filesystem API as disk/memory, including under MountFilesystem.

Example

>>> import io, zipfile
>>> from pyiv.files import ZipFilesystem
>>> buf = io.BytesIO()
>>> with zipfile.ZipFile(buf, "w") as zf:
...     zf.writestr("hello.txt", "hi")
>>> fs = ZipFilesystem(buf.getvalue())
>>> fs.read_text("/hello.txt")
'hi'
__init__(source: str | Path | bytes, *, mode: Literal['r', 'w', 'x', 'a'] = 'r') → None[source]

Open a zip from a path or in-memory bytes.

Parameters:
  • source – Path to a .zip file, or raw zip bytes

  • mode – r (read-only) or a / w when source is a path

copy(src: str | Path, dst: str | Path) → None[source]

Copy a file.

Parameters:
  • src – Source path

  • dst – Destination path

exists(path: str | Path) → bool[source]

Check if a path exists.

Parameters:

path – Path to check

Returns:

True if path exists, False otherwise

get_size(path: str | Path) → int[source]

Get file size in bytes.

Parameters:

path – File path

Returns:

File size in bytes

glob(pattern: str | Path) → Iterator[Path][source]

Glob pattern matching.

Parameters:

pattern – Glob pattern

Yields:

Matching paths

is_dir(path: str | Path) → bool[source]

Check if path is a directory.

Parameters:

path – Path to check

Returns:

True if path is a directory, False otherwise

is_file(path: str | Path) → bool[source]

Check if path is a file.

Parameters:

path – Path to check

Returns:

True if path is a file, False otherwise

listdir(path: str | Path) → Iterator[str][source]

List directory contents.

Parameters:

path – Directory path

Yields:

Directory entry names

mkdir(path: str | Path, parents: bool = False, exist_ok: bool = False) → None[source]

Create a directory.

Parameters:
  • path – Directory path

  • parents – Create parent directories if needed

  • exist_ok – Don’t raise error if directory exists

move(src: str | Path, dst: str | Path) → None[source]

Move/rename a file or directory.

Parameters:
  • src – Source path

  • dst – Destination path

open(file: str | Path, mode: str = 'r', encoding: str | None = None) → TextIO | BinaryIO[source]

Open a file.

Parameters:
  • file – File path

  • mode – File mode (r, w, a, rb, wb, etc.)

  • encoding – Text encoding (for text modes)

Returns:

File handle

read_bytes(path: str | Path) → bytes[source]

Read bytes from a file.

Parameters:

path – File path

Returns:

File contents as bytes

read_text(path: str | Path, encoding: str = 'utf-8') → str[source]

Read text from a file.

Parameters:
  • path – File path

  • encoding – Text encoding

Returns:

File contents as string

rmdir(path: str | Path) → None[source]

Remove a directory.

Parameters:

path – Directory path

Remove a file.

Parameters:
  • path – File path

  • missing_ok – Don’t raise error if file doesn’t exist

write_bytes(path: str | Path, content: bytes) → None[source]

Write bytes to a file.

Parameters:
  • path – File path

  • content – Bytes content to write

write_text(path: str | Path, content: str, encoding: str = 'utf-8') → None[source]

Write text to a file.

Parameters:
  • path – File path

  • content – Text content to write

  • encoding – Text encoding

pyiv.add_logging_args(parser: ArgumentParser) → None[source]

Add -v / -q / --log-level / --log-format to parser.

Why this exists: Commands share one CLI surface for log configuration.

Example

>>> import argparse
>>> p = argparse.ArgumentParser()
>>> add_logging_args(p)
>>> ns = p.parse_args(["-vv", "--log-format", "long"])
>>> ns.verbose
2
pyiv.get_injector(config: Type[Config] | Config, *, stage: Stage = Stage.DEVELOPMENT) → Injector[source]

Create an injector from a configuration class or instance.

Parameters:
  • config – A Config subclass or Config instance that defines dependencies

  • stage – DEVELOPMENT (default, lazy singletons) or PRODUCTION (eager)

Returns:

An Injector instance configured with the given config

Example

>>> from pyiv import Config, get_injector
>>> class Database:
...     pass
>>> class PostgreSQL(Database):
...     pass
>>> class MyConfig(Config):
...     def configure(self):
...         self.register(Database, PostgreSQL)
>>> isinstance(get_injector(MyConfig).inject(Database), PostgreSQL)
True
pyiv.get_optional_type(annotation: Any) → Type | None[source]

Extract the inner type from Optional[T].

Parameters:

annotation – The Optional[T] annotation

Returns:

The inner type T, or None if not Optional

pyiv.is_optional_type(annotation: Any) → bool[source]

Check if a type annotation is Optional[T].

Parameters:

annotation – The type annotation to check

Returns:

True if the annotation is Optional[T], False otherwise

pyiv.log_options_from_args(args: Any) → LogOptions[source]

Build LogOptions from an argparse namespace (or similar).

Example

>>> ns = argparse.Namespace(verbose=1, quiet=False, log_level="WARNING", log_format="short")
>>> log_options_from_args(ns).effective_level()
'INFO'
pyiv.override(*bases: Type[Config] | Config) → OverrideBuilder[source]

Start an override overlay over one or more base configs.

Example:

get_injector(override(ProdConfig).with_(TestConfig))
pyiv.package_version_domain(distribution: str) → str[source]

Return the version-domain key for an installed distribution name.

for_package_version / for_package_present / for_package_absent register sources under package:<distribution>. Tests override that domain with a MapVersionSource.

Example

>>> from pyiv.version import package_version_domain
>>> package_version_domain("requests")
'package:requests'