Skip to content

API Reference

Comprehensive API documentation for apywire.

Core Classes

Wiring

Wiring module-attribute

Wiring = WiringRuntime

WiringRuntime

WiringRuntime

Bases: WiringBase, ThreadSafeMixin

Runtime container for wired objects.

This class handles the runtime resolution and instantiation of wired objects. It does NOT support compilation; use WiringCompiler for that.

aio cached property

aio: 'AioAccessor'

Return a wrapper object providing async accessors.

Use await wired.aio.name() to obtain the instantiated value asynchronously. We use aio to avoid the reserved keyword async (so wired.async would be invalid syntax).

__getattr__

__getattr__(name: str) -> Accessor

Return a callable accessor for the named wired object.

__init__

__init__(
    spec: Spec,
    *,
    thread_safe: bool = False,
    max_lock_attempts: int = 10,
    lock_retry_sleep: float = 0.01
) -> None

Initialize a WiringRuntime container.

Parameters:

Name Type Description Default
spec Spec

The wiring spec mapping.

required
thread_safe bool

Enable thread-safe instantiation (default: False).

False
max_lock_attempts int

Max retries in global lock mode (only when thread_safe=True).

10
lock_retry_sleep float

Sleep time in seconds between lock retries (only when thread_safe=True).

0.01

WiringCompiler

WiringCompiler

Bases: WiringBase

Wiring container with compilation support.

compile

compile(
    *, aio: bool = False, thread_safe: bool = False
) -> str

Compiles the Spec into a string containing Python code.

Parameters:

Name Type Description Default
aio bool

If True, keep sync def accessors AND add an .aio cached property (CompiledAio wrapper). {aio.name} placeholders resolve to self.aio.name (async accessor attribute access).

False
thread_safe bool

If True, generate thread-safe accessors using ThreadSafeMixin.

False

Returns:

Type Description
str

A string containing the Python source for the compiled

str

Compiled container.

WiringBase

WiringBase

Bases: apywire.wiring.SpecParser

Base class for wiring containers.

__annotations__ class-attribute

__annotations__ = {
    "_parsed": "dict[str, _ParsedEntry]",
    "_values": "dict[str, _RuntimeValue]",
}

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__doc__ class-attribute

__doc__ = 'Base class for wiring containers.'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__module__ class-attribute

__module__ = 'apywire.wiring'

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__init__ method descriptor

__init__(
    spec: dict,
    *,
    thread_safe: bool = False,
    max_lock_attempts: int = 10,
    lock_retry_sleep: float = 0.01
) -> None

Initialize a Wiring container.

Parameters:

Name Type Description Default
spec dict

The wiring spec mapping.

required
thread_safe bool

Enable thread-safe instantiation (default: False).

False
max_lock_attempts int

Max retries in global lock mode (only when thread_safe=True).

10
lock_retry_sleep float

Sleep time in seconds between lock retries (only when thread_safe=True).

0.01

Generator

Generator

Bases: SpecParser

Generates apywire specs from class introspection.

This class inspects class constructors to automatically generate spec dictionaries with type-appropriate default values and placeholder references.

Example

spec = Generator.generate("datetime.datetime now")

Returns spec with now_year, now_month, now_day, etc.

generate classmethod

generate(*entries: str) -> Spec

Generate a spec from one or more class entry strings.

Parameters:

Name Type Description Default
*entries str

Entry strings in format "module.Class name" or "module.Class name.factoryMethod"

()

Returns:

Type Description
Spec

A spec dictionary suitable for use with apywire.Wiring

Raises:

Type Description
ValueError

If entry format is invalid

Example

spec = Generator.generate("datetime.datetime now") wired = Wiring(spec)

Accessor Types

Accessor

Accessor

A callable object that retrieves a wired value.

__call__

__call__() -> object

Return the wired object, instantiating it if necessary.

AioAccessor

AioAccessor

Helper for accessing wired objects asynchronously.

__getattr__

__getattr__(name: str) -> Callable[[], Awaitable[object]]

Return an async callable for the named wired object.

CompiledAio

CompiledAio

Async accessor wrapper for compiled containers.

Wraps a compiled container's sync methods with async access. Cached values are returned directly; uncached values are resolved via run_in_executor to avoid blocking the event loop.

__getattr__

__getattr__(name: str) -> Callable[[], Awaitable[object]]

Return an async callable for the named accessor.

Type Aliases

Spec

from apywire import Spec

Spec = dict[str, dict[str | int, Any] | list[Any] | ConstantValue]

The Spec type represents the wiring specification dictionary. It maps wiring keys to configuration:

  • Wiring keys with format "module.Class name" define objects to be wired
  • Simple keys without a class become constants
  • Values can be dictionaries (keyword args), lists (positional args), or constants

Example:

from apywire import Spec

spec: Spec = {
    "datetime.datetime now": {"year": 2025, "month": 1, "day": 1},
    "pathlib.Path root": ["/home/user"],
    "port": 8080,  # Constant
}

SpecEntry

from apywire import SpecEntry

SpecEntry = dict[str | int, Any]

The SpecEntry type represents a single entry in the spec (the configuration for one wired object):

from apywire import SpecEntry

entry: SpecEntry = {
    "year": 2025,
    "month": 1,
    "day": 1,
}

Exception Classes

WiringError

WiringError

Bases: AttributeError

Raised when the wiring system cannot instantiate an attribute.

This wraps the underlying exception to provide context on which attribute failed to instantiate, while preserving the original exception as the cause.

Base exception class for all apywire errors.

CircularWiringError

CircularWiringError

Bases: WiringError

Raised when a circular wiring dependency is detected.

This class is a WiringError subtype for simpler programmatic handling of wiring-specific failures.

Utility: construct a helpful message from a dependency mapping and unprocessed nodes when a topological sort fails.

from_unprocessed classmethod

from_unprocessed(
    dependencies: dict[str, set[str]],
    unprocessed: list[str],
) -> CircularWiringError

Create a CircularWiringError that includes a cycle when possible.

Parameters:

Name Type Description Default
dependencies dict[str, set[str]]

Full mapping of node -> dependencies

required
unprocessed list[str]

List of nodes left unprocessed by topological sort

required

Returns:

Type Description
CircularWiringError

CircularWiringError instance with a helpful message.

Raised when a circular dependency is detected; see Circular dependencies for examples and mitigation strategies:

from apywire import CircularWiringError, Wiring

spec = {
    "MyClass a": {"dep": "{b}"},
    "MyClass b": {"dep": "{a}"},
}

try:
    wired = Wiring(spec)
except CircularWiringError as e:
    print(f"Circular dependency: {e}")

UnknownPlaceholderError

UnknownPlaceholderError

Bases: WiringError

Raised by _resolve_runtime when a placeholder name is not found in either constants (_values) or parsed spec entries (_parsed).

Raised when a placeholder references a non-existent object:

from apywire import UnknownPlaceholderError, Wiring

spec = {
    "MyClass obj": {"dep": "{nonexistent}"},
}

wired = Wiring(spec)
try:
    obj = wired.obj()
except UnknownPlaceholderError as e:
    print(f"Unknown placeholder: {e}")

LockUnavailableError

LockUnavailableError

Bases: RuntimeError

Exception raised when a per-attribute lock cannot be acquired in optimistic (non-blocking) mode and the code must fall back to a global lock.

This exception is used internally by the thread-safety system but is also referenced in compiled code, so it is part of the public API.

Raised in thread-safe mode when a lock cannot be acquired after maximum retry attempts:

from apywire import LockUnavailableError, Wiring

wired = Wiring(spec, thread_safe=True, max_lock_attempts=1)

try:
    obj = wired.my_object()
except LockUnavailableError as e:
    print(f"Could not acquire lock: {e}")

Usage Examples

Basic Wiring

from apywire import Wiring

spec = {
    "datetime.datetime now": {"year": 2025, "month": 1, "day": 1},
}

wired = Wiring(spec)
dt = wired.now()  # datetime.datetime(2025, 1, 1, 0, 0)

Async Access

import asyncio
from apywire import Wiring

async def main():
    wired = Wiring(spec)
    obj = await wired.aio.my_object()

asyncio.run(main())

Thread-Safe Instantiation

from apywire import Wiring

wired = Wiring(spec, thread_safe=True)
# Safe to use across multiple threads

Code Compilation

from apywire import WiringCompiler

compiler = WiringCompiler(spec)
code = compiler.compile(aio=True, thread_safe=True)

with open("compiled_wiring.py", "w") as f:
    f.write(code)

Generator (Spec Generator)

from apywire import Generator, Wiring

# Generate a spec from a class signature
spec = Generator.generate("myapp.models.Simple now")

# Override a generated default if needed
spec["now_year"] = 2025

wired = Wiring(spec)
now = wired.now()

See Also