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),Annotatedconstructor injection, and BinderVersion-conditioned bindings (
for_version/for_package_version/for_package_present/for_package_absent/for_python_version) over named version domainsModule 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) TrueMultiple 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; useinject(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:
ABCInjectable program arguments and exit reporting.
Why this exists: CLI code that reads
sys.argvor callssys.exitis awkward in unit tests. InjectArgvinstead.Example
>>> from pyiv.process import MemoryArgv >>> argv: Argv = MemoryArgv(["prog", "--verbose"]) >>> list(argv.args) ['prog', '--verbose']
- class pyiv.AsyncHttpClient[source]
Bases:
ABCAsync 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
AsyncUrllibHttpClientorMemoryAsyncHttpClient.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 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:
AsyncHttpClientAsync HTTP client that runs
UrllibHttpClientin a thread pool.Why this exists: Async apps can inject an HTTP client without httpx. Blocking urllib I/O runs via
run_in_executorso 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]
- class pyiv.Base64SerDe[source]
Bases:
SerDeBase64 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
- class pyiv.BaseConsole[source]
Bases:
ABCAbstract base class for console implementations.
Subclass this when you need a custom
Console(file-like write plus optional TTY helpers). Implementwrite/flush/writable; terminal methods default to no-ops so simple sinks stay small. PreferMemoryConsolefor capturingprint()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'
- get_events() List[TerminalEvent][source]
Get event history (default: empty list).
- 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_style() Dict[str, bool][source]
Get text style state (default: all False).
- Returns:
Dictionary of style flags
- read_char(timeout: float | None = None) str | None[source]
Read a single character (default: None).
- read_password(prompt: str = '') str[source]
Read password with echo disabled (default: empty string).
- set_color(fg: int | None = None, bg: int | None = None) None[source]
Set foreground and/or background color (no-op by default).
- class pyiv.BaseFactory[source]
-
ABC when you want a class-based factory with constructor injection.
Why this exists: Protocols are fine for typing; subclassing
BaseFactorygives a real type the injector can construct, with dependencies supplied to__init__and runtime args tocreate.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'
- class pyiv.BaseProvider[source]
-
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'
- class pyiv.Binder(*args, **kwargs)[source]
Bases:
ProtocolFluent configuration API for contributing bindings to a
Config.Why this exists: Direct
Config.register*calls work, but complex graphs read better asbind(X).to(Y).in_scope(Z). The binder also supportsinstall,expose, version-conditioned bindings (includingfor_package_present/for_package_absent), andrequire_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).Matchedis inject-only and rejected at registration. Duplicate Named tag sets for the same type raise; at most oneNamed(..., default=True)per type is allowed.- Parameters:
key – The qualified key to bind (
Named, notMatched)- 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).
- class pyiv.BindingBuilder(*args, **kwargs)[source]
-
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 sameConfigstore (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.versionfor 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 whenimportlib.metadatareports the distribution as missing. Pair withfor_package_present()for an explicit both-sides choice, or use an unconditional fallback afterfor_package_presentinstead.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 withfor_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_versionwithPackageVersionSourceand the built-in"PEP440"Pep440VersionParser.Pass
PACKAGE_PRESENT("*") /PACKAGE_ABSENT("!") — or usefor_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 namespecifier – 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
BindingBuilderclass docstring for a runnablefor_python_versionexample (withFixedPythonVersionProvider).- 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(), orfor_package_absent()when those cover the domain. Seepyiv.versionand the version-bindings guide.- Parameters:
domain – Named version domain (must have a
VersionSource)specifier – Domain-specific version constraint string (or
PACKAGE_PRESENT/PACKAGE_ABSENTfor package domains)parser – Optional named
VersionParser(defaults to the domain’s parser, then"PEP440")
- 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:
CommandBase class for one-shot CLI commands (not long-running services).
Use this for tools that init, run once, and exit. Override
run()(and optionallyinit()/cleanup()); setself._exit_codefor non-zero status. Do not overrideexecute()— 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.
- class pyiv.ChainHandler[source]
Bases:
ABCPluggable 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
Configand resolve them withinject_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
- class pyiv.ChainType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
EnumCategory 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.
ChainTypenamespaces 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:
ABCAbstract 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
- class pyiv.Command(args: Namespace, injector: Any | None = None)[source]
Bases:
ABCBase 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
CLICommandfor one-shot tools andServiceCommandfor 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-formatflags.Call from
add_argswhen the command should configurepyiv.log. Apply options ininitviaconfigure_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
LogOptionsfromself.argsusingLogSetup.Prefer injecting
LogSetupfrom the injector when available; falls back to a process-localLogSetupinstance.
- 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.
- class pyiv.CommandRunner(config: Any | None = None)[source]
Bases:
objectDiscovers and runs
Commandsubclasses 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:
objectResult of a process run (stdlib-shaped, frozen).
Why this exists: Boring DTO for assertions and Settings round-trip.
Example
>>> CompletedProcess(["true"], 0).returncode 0
- class pyiv.Config[source]
Bases:
objectModule 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, overrideconfigure(), and register interfaces → implementations (or useget_binder()). For plugin catalogs, prefercontribute_map()/map_multibinderso 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
- 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_versionhelpers 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:
PACKAGE_ABSENTmatches when the source returnsNone;PACKAGE_PRESENTmatches any non-None version (no parser)otherwise filter by domain
VersionSource+ namedVersionParserexactly one match → register that binding (scope/provider preserved)
zero matches → keep any unconditional binding as fallback; otherwise raise
CreationErrortwo or more matches → raise ambiguous
CreationError
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(...).addwhen 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;
PrivateConfiguses the set when installed into a parent.
- 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
VersionParserregistered asname.
- 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
Namedtag sets,replace=Trueoverwrites; twodefault=TrueNamed bindings for the same type raise.PrivateConfiginstances 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
otherinto this config.- Parameters:
other – Source config
replace – If True,
otheroverwrites 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:
TypeError – If instance is not a ChainHandler
ValueError – If name is empty
- 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.Matchedis inject-only and rejected here.For
Namedkeys of the same type:Duplicate tag sets raise
ValueErrorunlessreplace=True(used byinstall/ merge).At most one
Named(..., default=True)per type is allowed.
- Parameters:
key – The qualified key (
Namedfor multi-impl; notMatched)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
MatchedValueError – On duplicate Named tag set (without replace) or a second
default=Truefor 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 withuse_version_parser()orfor_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.
- resolve_version_parser(domain: str, parser_name: str | None = None) Any[source]
Resolve the parser for a domain (candidate override → domain → PEP440).
- class pyiv.Console(*args, **kwargs)[source]
Bases:
ProtocolProtocol 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)
- clear_state() None[source]
Clear all state (for test setup).
Resets terminal state including screen buffer, cursor position, colors, styles, and event history.
- 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.)
- 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)
- 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
- 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
- exception pyiv.CreationError(message: str, *, path: Sequence[str] | None = None, causes: Sequence[BaseException] | None = None, ambiguous: bool = False)[source]
Bases:
ExceptionRaised 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 -> Databaseinstead of a bareValueError.- 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
- class pyiv.DateTimeService[source]
Bases:
ABCAbstract interface for UTC datetime operations.
Depend on this instead of calling
datetime.nowdirectly so production code can usePythonDateTimeServicewhile tests injectMockDateTimeServicewith 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'
- class pyiv.Entropy[source]
Bases:
ABCInjectable source of randomness.
Why this exists:
secrets/randomat call sites make tests flaky. InjectEntropyand bindSyntheticEntropywith a seed.Example
>>> from pyiv.entropy import SyntheticEntropy >>> e: Entropy = SyntheticEntropy(seed=1) >>> len(e.randbytes(4)) 4
- class pyiv.Environment[source]
Bases:
ABCInjectable view of process environment variables.
Why this exists: Mutating
os.environin tests leaks across cases. Depend onEnvironmentand bindMemoryEnvironmentin tests.Example
>>> from pyiv.process import MemoryEnvironment >>> env: Environment = MemoryEnvironment({"A": "1"}) >>> env.get("A") '1'
- class pyiv.ExitStatus(code: int = 0)[source]
Bases:
objectRecorded process exit code.
Why this exists: Capture
sys.exitintent without terminating tests.Example
>>> ExitStatus(2).code 2
- class pyiv.Factory(*args, **kwargs)[source]
-
Callable creation API for objects that need runtime arguments.
Why this exists: A DI
Providerbuilds one graph-managed instance. AFactorycreates 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)
- 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
- class pyiv.FileConsole(file: str | Path, mode: str = 'w', encoding: str = 'utf-8')[source]
Bases:
BaseConsoleFile-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)
- class pyiv.Filesystem[source]
Bases:
ABCAbstract filesystem for injectable file I/O.
Why this exists: Production code that calls
open()/pathlibdirectly is hard to unit-test without touching disk or mocking builtins. Depend onFilesystemand bindRealFilesystemin production andMemoryFilesystemin 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
- abstract unlink(path: str | Path, missing_ok: bool = False) None[source]
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.
- class pyiv.FixedPythonVersionProvider(version: str)[source]
Bases:
PythonVersionProviderTest 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'
- class pyiv.GlobalSingletonRegistry[source]
Bases:
objectProcess-wide store for
GLOBAL_SINGLETONinstances.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
- class pyiv.GlobalSingletonScope[source]
Bases:
objectGlobal 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)
- class pyiv.Hasher[source]
Bases:
ABCInjectable digest / HMAC helper.
Why this exists: Call sites that hard-code
hashlibare 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'
- class pyiv.HttpClient[source]
Bases:
ABCSync 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
UrllibHttpClientin production andMemoryHttpClientin 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'
- 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.
- exception pyiv.HttpError[source]
Bases:
ExceptionBase 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:
objectBuffered 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()
- json() Any[source]
Parse the body as JSON.
- Returns:
The decoded JSON value
- Raises:
json.JSONDecodeError – If the body is not valid JSON
- exception pyiv.HttpStatusError(message: str, *, status_code: int, response: HttpResponse)[source]
Bases:
HttpErrorThe 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'
- exception pyiv.HttpTimeoutError[source]
Bases:
HttpErrorThe 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:
objectResolves types and keys from a
Configgraph.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_typewithout 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)``):
Unqualified registration / instance / provider for the type
Else
Namedbindings for that type: the soledefault=Truebinding, or the only Named binding if there is exactly one; multiple Named bindings without a unique default raiseElse parent injector (if any)
Else JIT for concrete types (unless explicit bindings required)
Resolution for keys:
Key(T, Named(...))— strict exact tag-set matchKey(T, Matched(required=..., prefer=...))— nearest match among Named bindings (required ⊆ tags, max prefer overlap, then default)Custom qualifiers — exact
Keylookup only
Ambiguous Named resolution raises
CreationError(including when resolvingOptional[T]constructor deps — ambiguity is not absence).Constructor parameters may use
AnnotatedwithNamedorMatched(and optionallyProvider[T]/Optional[T]) on Python 3.9+ (or withtyping_extensions.Annotatedon 3.8). Annotated qualifiers apply only when resolving constructor / factory parameters — not oninject_membersfields, not as the argument toinject()itself, andMatchedis 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]/Matchedon fields is ignored — use constructor Annotated params or assignself.inject(Key(...))manually.
- named_keys(binding_type: Type[T]) List[Named][source]
Return
Namedqualifiers bound forbinding_typewithout 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']]
- 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 callinjector.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 forAnnotated[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'
- 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'
- exception pyiv.InvalidSpecifier[source]
Bases:
InvalidVersionRaised when a version constraint / specifier string is invalid.
Why this exists: Distinguishes bad constraints (
>>>>1.0) from bad version strings while remaining catchable asInvalidVersion.Example
>>> from pyiv.version import InvalidSpecifier, InvalidVersion >>> issubclass(InvalidSpecifier, InvalidVersion) True
- exception pyiv.InvalidVersion[source]
Bases:
ValueErrorBase error for
VersionParserparse 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:
SerDeStandard JSON SerDe using Python’s
jsonmodule.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
- 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
Namedwhen binding (and for strict inject). UseMatchedonly when injecting for nearest-match resolution.Prefer
Annotated[T, Named|Matched]on constructors when the dependency is a parameter; useinject(Key(...))for explicit lookups. Annotated qualifiers are not applied duringinject_membersfield 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
- 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
- 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:
objectConfiguration for
LogSetup.apply.Why this exists: CLI flags and host Settings need a boring frozen bag — not
dictConfigsprawl — without a pydantic dependency.Example
>>> opts = LogOptions(level="DEBUG", verbose=1) >>> opts.as_dict()["level"] 'DEBUG'
- class pyiv.LogSetup(stream=None)[source]
Bases:
objectConfigure root logging from
LogOptions(idempotent replace).Why this exists: CLI
-v/--log-levelshould apply once without fighting duplicate handlers or hand-rolledbasicConfig.Example
>>> from pyiv.log import LogOptions, LogSetup >>> LogSetup().apply(LogOptions(level="INFO", format_style="short"))
- apply(options: LogOptions) None[source]
Replace pyiv-managed root handlers with options-derived config.
- class pyiv.Logger[source]
Bases:
ABCInjectable diagnostic logger.
Why this exists: Services should not call
logging.getLoggerdirectly 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 exception(msg: str, *args: Any, **kwargs: Any) None[source]
Log an error with exception info.
- class pyiv.LoggerFactory[source]
Bases:
ABCCreate named
Loggerinstances.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
- 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, prefercontribute_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
- class pyiv.MapVersionSource(versions: Mapping[str, str], *, domain: str | None = None)[source]
Bases:
objectFixed version map for tests and host-supplied environment snapshots.
Why this exists: Selection must be deterministic in unit tests without monkeypatching
sysorimportlib.metadata. Use it forfor_package_versionranges and to simulate an installed distribution forfor_package_present(register underpackage_version_domain()). Bind one domain key, or pass a multi-key map and select withdomain.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'
- class pyiv.MappingFilesystem(data: Mapping[str, str | bytes] | None = None)[source]
Bases:
FilesystemExpose a string→bytes (or str) mapping as a flat file tree under
/.Why this exists: Pattern for external adapters (DB row as
/procfile) without putting SQL in core. Mount underMountFilesystem.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'
- 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
- unlink(path: str | Path, missing_ok: bool = False) None[source]
Remove a file.
- Parameters:
path – File path
missing_ok – Don’t raise error if file doesn’t exist
- class pyiv.Matched(required: str | Sequence[str] | None = None, prefer: str | Sequence[str] | None = None)[source]
Bases:
objectInject-only qualifier for required/prefer tag matching.
Why this exists: Exact
Namedkeys are rigid when several bindings share tags.Matchedselects amongNamedregistrations: everyrequiredtag must be present, then the binding with the mostpreferoverlap wins;Named(..., default=True)breaks remaining ties. Frozen dataclass shape stays pydantic-friendly without a pydantic dependency.Do not pass
Matchedtoregister_key/bind_key— registration usesNamedonly.Constructor injection:
Annotated[T, Matched(...)]on__init__(includingAnnotated[Optional[T], Matched(...)]). Not supported on field /inject_memberspaths.Resolution ladder (candidates = all Named bindings for the key type):
Keep bindings where
required ⊆ binding.tagsKeep those with maximal
|prefer ∩ binding.tags|If still more than one, keep
default=TrueExactly 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:
TypeError – If a tag is not a string
ValueError – If a tag string is empty
- class pyiv.MembersInjector(*args, **kwargs)[source]
-
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)
- class pyiv.MemoryArgv(args: Sequence[str] | None = None)[source]
Bases:
ArgvIn-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
- class pyiv.MemoryAsyncHttpClient(base_url=None, headers=None, sync_client=None, options=None)[source]
Bases:
AsyncHttpClientAsync 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'
- 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]
- class pyiv.MemoryConsole[source]
Bases:
BaseConsoleIn-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'
- close() None[source]
Close the buffer.
Note: After closing, getvalue() will raise ValueError. To get the value before closing, call getvalue() first.
- 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
- class pyiv.MemoryEnvironment(initial: Mapping[str, str] | None = None)[source]
Bases:
EnvironmentIn-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'
- class pyiv.MemoryFilesystem[source]
Bases:
FilesystemIn-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'
- 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:
FileExistsError – If directory or file exists at path and exist_ok is False
FileNotFoundError – If parent directory doesn’t exist and parents is False
- 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:
FileNotFoundError – If file doesn’t exist in read mode
ValueError – If mode is unsupported
- 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:
FileNotFoundError – If directory doesn’t exist
ValueError – If trying to remove root directory
OSError – If directory is not empty
- unlink(path: str | Path, missing_ok: bool = False) None[source]
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
- class pyiv.MemoryHttpClient(base_url=None, headers=None, options=None)[source]
Bases:
HttpClientSync 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'
- 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]
- class pyiv.MemoryLogSetup[source]
Bases:
objectNo-op setup for tests that use
MemoryLoggeronly.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:
LoggerIn-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']
- class pyiv.MemoryLoggerFactory[source]
Bases:
LoggerFactoryFactory that returns shared
MemoryLoggerinstances by name.Why this exists: Tests inject one factory and assert per-name records.
- class pyiv.MemoryProcessRunner[source]
Bases:
ProcessRunnerScripted 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'
- run(argv: Sequence[str], *, options: RunOptions | None = None) CompletedProcess[source]
Run
argvand return a completed process result.
- class pyiv.MockConsole(width: int = 80, height: int = 24)[source]
Bases:
BaseConsoleTerminal 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
- get_color() Tuple[int | None, int | None][source]
Get current color state.
- Returns:
Tuple of (fg, bg)
- get_cursor_position() Tuple[int, int] | None[source]
Get current cursor position.
- Returns:
Tuple of (x, y)
- get_events() List[TerminalEvent][source]
Get event history.
- Returns:
List of terminal events
- 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
- is_tty() bool[source]
Check if console is a TTY (always False for mock).
- Returns:
False (mock console is not a real TTY)
- 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)
- set_color(fg: int | None = None, bg: int | None = None) None[source]
Set foreground and/or background color.
- simulate_input(text: str) None[source]
Simulate input for testing.
- Parameters:
text – Text to add to input buffer
- class pyiv.MockDateTimeService(fixed_time: datetime | None = None)[source]
Bases:
DateTimeServiceMock 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
- class pyiv.MountFilesystem(root: Filesystem | None = None)[source]
Bases:
FilesystemPath-prefix router over nested
Filesysteminstances.Why this exists: Expose virtual trees (fake
/proc, zip mounts, etc.) beside a real or memory root without monkeypatchingopen.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
filesystematmount_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
- unlink(path: str | Path, missing_ok: bool = False) None[source]
Remove a file.
- Parameters:
path – File path
missing_ok – Don’t raise error if file doesn’t exist
- class pyiv.MountPoint(mount_path: str, filesystem: Filesystem)[source]
Bases:
objectA 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
- class pyiv.Multibinder(*args, **kwargs)[source]
-
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)
- class pyiv.Named(name: str | Sequence[str], *, default: bool = False)[source]
Bases:
objectTag-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=Truemarks the binding used for bareinject(Type)and forMatchedtie-breaks. Frozen dataclass shape stays pydantic-friendly without a pydantic dependency.Accepts
str,list, ortuple; all normalize to a frozenset.Named("json") == Named(["json"]). Equality and hashing use the tag set only —defaultis binding metadata, not part of key identity.Register with
Namedonly. For nearest-match inject, useMatched.Constructor injection: use
Annotated[T, Named(...)]on__init__parameters (also withOptional[T]/Provider[T]). This does not apply to field /inject_membersinjection — 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
- class pyiv.NoOpSerDe[source]
Bases:
SerDeNo-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
- class pyiv.NoScope[source]
Bases:
objectNo 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())
- class pyiv.OsEnvironment[source]
Bases:
EnvironmentEnvironment backed by
os.environ.Why this exists: Production binding for real process env.
- class pyiv.PTYConsole[source]
Bases:
BaseConsolePseudoterminal 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
- get_cursor_position() Tuple[int, int] | None[source]
Get cursor position (not easily available from pty).
- Returns:
None (not implemented for pty)
- get_events() List[TerminalEvent][source]
Get event history (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_style() Dict[str, bool][source]
Get text style state (not available for PTYConsole).
- Returns:
Dictionary with all styles False
- is_tty() bool[source]
Check if pty is a terminal (always True).
- Returns:
True (pty always behaves as TTY)
- 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)
- class pyiv.PackageVersionSource(distribution: str)[source]
Bases:
objectRead an installed distribution version via
importlib.metadata.Why this exists:
for_package_version,for_package_present, andfor_package_absentneed 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.Nonemeans absent and is whatfor_package_absentmatches 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
- class pyiv.Pep440VersionParser[source]
Bases:
objectVersionParserimplementation for PEP 440.Why this exists: Python package and interpreter domains need a named, standards-based parser. Config registers this under
pyiv.version.PEP440by default sofor_package_version/for_python_versionwork without extra setup. Presence / absence (for_package_present/for_package_absent) do not use this parser — they short-circuit onPACKAGE_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
versionsatisfies the PEP 440specifier.- Raises:
InvalidVersion – If
versionorspecifieris not PEP 440.
- class pyiv.PickleSerDe[source]
Bases:
SerDePython 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
- class pyiv.PrivateConfig[source]
Bases:
ConfigConfig 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
- class pyiv.ProcessRunner[source]
Bases:
ABCInjectable subprocess runner.
Why this exists: Call sites that use
subprocess.runare hard to unit-test. InjectProcessRunnerand bindMemoryProcessRunner.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
argvand return a completed process result.
- class pyiv.Provider(*args, **kwargs)[source]
-
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)
- class pyiv.PythonDateTimeService[source]
Bases:
DateTimeServiceDateTime service backed by the system clock.
Use this in production for real UTC timestamps. In tests, swap in
MockDateTimeServiceso 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
- class pyiv.PythonVersionProvider[source]
Bases:
ABCInjectable source of the running (or simulated) Python version.
Why this exists:
for_python_versionand application code that branches on the interpreter must not hard-codesys.version_info. BindSysPythonVersionProviderin production andFixedPythonVersionProviderin 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'
- class pyiv.PythonVersionSource(provider: PythonVersionProvider | None = None, *, config: 'Config' | None = None)[source]
Bases:
objectVersionSourcethat delegates to aPythonVersionProvider.Why this exists:
for_python_versionregisters this as thepythondomain source. At selection time it resolves (in order): an explicit constructor provider, aPythonVersionProviderbound on the config, thenSysPythonVersionProvider.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.
- class pyiv.Qualifier(*args, **kwargs)[source]
Bases:
ProtocolMarker for distinguishing multiple bindings of the same type.
Why this exists: One interface often has several implementations (primary vs replica DB). A qualifier +
Keyselects 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:
ClockReal 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
- class pyiv.RealConsole(stream: TextIO | None = None, stdin: TextIO | None = None)[source]
Bases:
BaseConsoleProduction 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
- 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_style() Dict[str, bool][source]
Get text style state (not available for RealConsole).
- Returns:
Dictionary with all styles False
- 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)
- 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
- 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
- class pyiv.RealEntropy[source]
Bases:
EntropyEntropy backed by
secrets/random.Why this exists: Production cryptographic-ish tokens via stdlib.
- class pyiv.RealFilesystem(root: str | Path | None = None)[source]
Bases:
FilesystemReal filesystem implementation using the standard library.
Use this in production when you need actual disk I/O. Prefer
MemoryFilesystemin unit tests so examples and CI never write into the working tree. Optionalroot=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'
- 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)
- unlink(path: str | Path, missing_ok: bool = False) None[source]
Remove a file.
- Parameters:
path – File path to remove
missing_ok – Don’t raise error if file doesn’t exist
- class pyiv.RealHasher[source]
Bases:
HasherHasher backed by
hashlib/hmac.Why this exists: Production digests via the standard library.
- class pyiv.RealProcessRunner[source]
Bases:
ProcessRunnerProcess 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
argvand return a completed process result.
- class pyiv.ReflectionConfig[source]
Bases:
ConfigConfiguration that discovers implementations in packages via reflection.
Why this exists: Auto-discover interface implementations in a package instead of listing every class. Use
as_multibindwhen 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_registrationsmust exist beforeConfig.__init__runsconfigure(), which may callregister_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
registerpath (ignored whenas_multibindis set)as_multibind – If
None(default), each discovery callsregister(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_attror 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:
objectOptions for a single
ProcessRunner.runcall.Why this exists: Frozen knob for Settings nesting without pydantic.
Example
>>> RunOptions(timeout=1.0).as_dict()["timeout"] 1.0
- class pyiv.Scope(*args, **kwargs)[source]
Bases:
ProtocolProtocol 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)
- class pyiv.SerDe[source]
Bases:
ChainHandlerAbstract 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_typeinstead of hard-codingjson.dumps/pickle.loads. Register implementations on the ENCODING chain so injectors and pipelines can swap formats without rewriting call sites. Multiple handlers may share ahandler_typewith different behaviors (date formatting, null handling, and so on).Subclasses must implement
handler_type,serialize, anddeserialize.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
- class pyiv.ServiceCommand(args: Namespace, injector: Any | None = None)[source]
Bases:
CommandBase class for long-running service commands.
Use this when a command should run until interrupted (daemons, workers).
execute()runsinit()→run()→cleanup()and mapsKeyboardInterruptto 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
- 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
- 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'
- class pyiv.SingletonScope[source]
Bases:
objectPer-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())
- class pyiv.SingletonType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
EnumLegacy enum for singleton lifecycle on
Config.register.Why this exists: Older call sites use
singleton_type=...instead of aScope. PreferScopefor 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:
EnumInjector construction stage: lazy vs fail-fast singletons.
Why this exists: Lazy singletons hide binding mistakes until first use. Pass
stage=Stage.PRODUCTIONtoget_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:
LoggerLogger wrapping a stdlib
logging.Logger.Why this exists: Production emit path that still participates in the stdlib hierarchy (third-party libs keep working).
- class pyiv.StdlibLoggerFactory[source]
Bases:
LoggerFactoryFactory wrapping
logging.getLogger.Why this exists: Production factory that stays on the stdlib hierarchy.
- class pyiv.SyntheticClock(start_time: float = 0.0)[source]
Bases:
ClockSynthetic 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
- class pyiv.SyntheticEntropy(seed: int | None = None)[source]
Bases:
EntropySeeded 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
- class pyiv.SyntheticHasher(fixed: bytes | None = None)[source]
Bases:
HasherHasher 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'
- class pyiv.SysArgv[source]
Bases:
ArgvArgv backed by
sys.argv/sys.exit.Why this exists: Production binding for real CLI entrypoints.
- class pyiv.SysPythonVersionProvider[source]
Bases:
PythonVersionProviderProduction
PythonVersionProviderbacked bysys.version_info.Why this exists: Default for
for_python_versionwhen no test provider is bound. Prefer injectingPythonVersionProviderover 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.microforsys.version_info.
- class pyiv.TarFilesystem(source: str | Path | bytes)[source]
Bases:
FilesystemTreat a tar archive as a read-oriented
Filesystemtree.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'
- 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
- unlink(path: str | Path, missing_ok: bool = False) None[source]
Remove a file.
- Parameters:
path – File path
missing_ok – Don’t raise error if file doesn’t exist
- class pyiv.Timer[source]
Bases:
ABCAbstract handle for a scheduled callback.
Use timers when code needs one-shot or repeating callbacks driven by a
Clock. PreferSyntheticClock.start_timerin tests so time advances only when you calladvance(), 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()
- class pyiv.UrllibHttpClient(base_url=None, headers=None, timeout=None, https_only=False, options=None)[source]
Bases:
HttpClientHTTP(S) client using stdlib
urllib.Why this exists: Core pyiv stays zero-dependency. This is the default production
HttpClientwhen 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
- 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:
objectOne version-conditioned alternative for an abstract type.
Why this exists: Unconditional
Configregistrations 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 — preferbinder.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 '*'
- class pyiv.VersionParser(*args, **kwargs)[source]
Bases:
ProtocolParses 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 withpyiv.binder.Binder.use_version_parser(). RaiseInvalidVersion(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
versionsatisfiesspecifierfor this grammar.- Raises:
InvalidVersion – If
versionorspecifiercannot be parsed.
- class pyiv.VersionSource(*args, **kwargs)[source]
Bases:
ProtocolProvides 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
MapVersionSourcein tests.Example
>>> from pyiv.version import MapVersionSource >>> src = MapVersionSource({"alpine": "3.19.0"}) >>> src.get_version() '3.19.0'
- __init__(*args, **kwargs)
- class pyiv.XMLSerDe[source]
Bases:
SerDeXML 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
itemchildren. 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)
- class pyiv.ZipFilesystem(source: str | Path | bytes, *, mode: Literal['r', 'w', 'x', 'a'] = 'r')[source]
Bases:
FilesystemTreat a ZIP archive as a
Filesystemtree (read; write when writable).Why this exists: Apps that read config or assets from a zip should inject the same
FilesystemAPI as disk/memory, including underMountFilesystem.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
.zipfile, or raw zip bytesmode –
r(read-only) ora/wwhensourceis 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
- unlink(path: str | Path, missing_ok: bool = False) None[source]
Remove a file.
- Parameters:
path – File path
missing_ok – Don’t raise error if file doesn’t exist
- pyiv.add_logging_args(parser: ArgumentParser) None[source]
Add
-v/-q/--log-level/--log-formattoparser.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
LogOptionsfrom 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_absentregister sources underpackage:<distribution>. Tests override that domain with aMapVersionSource.Example
>>> from pyiv.version import package_version_domain >>> package_version_domain("requests") 'package:requests'