API Reference¶
Comprehensive API documentation for apywire.
Core Classes¶
Wiring¶
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
¶
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__ ¶
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 ¶
Compiles the Spec into a string containing Python code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
aio
|
bool
|
If True, generate |
False
|
Returns:
| Type | Description |
|---|---|
str
|
A string containing the Python source for the compiled |
str
|
|
WiringBase¶
WiringBase ¶
Base class for wiring containers.
__annotations__
class-attribute
¶
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)
__dict__
class-attribute
¶
__dict__ = mappingproxy({'__module__': 'apywire.wiring', '__doc__': 'Base class for wiring containers.', '__annotations__': {'_parsed': 'dict[str, _ParsedEntry]', '_values': 'dict[str, _RuntimeValue]'}, '__init__': <cyfunction WiringBase.__init__ at 0x7f337ad44ae0>, '_parse_spec_entry': <cyfunction WiringBase._parse_spec_entry at 0x7f337ad44a10>, '_is_placeholder': <cyfunction WiringBase._is_placeholder at 0x7f337ad44c80>, '_extract_placeholder_name': <cyfunction WiringBase._extract_placeholder_name at 0x7f337ad44d50>, '_resolve': <cyfunction WiringBase._resolve at 0x7f337ad44e20>, '_interpolate_placeholders': <cyfunction WiringBase._interpolate_placeholders at 0x7f337ad44ef0>, '_find_placeholder_names': <cyfunction WiringBase._find_placeholder_names at 0x7f337ad44fc0>, '_topological_sort': <cyfunction WiringBase._topological_sort at 0x7f337ad44bb0>, '_resolve_constant': <cyfunction WiringBase._resolve_constant at 0x7f337ad45090>, '__dict__': <attribute '__dict__' of 'WiringBase' objects>, '__weakref__': <attribute '__weakref__' of 'WiringBase' objects>})
Read-only proxy of a mapping.
__doc__
class-attribute
¶
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
¶
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 ¶
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 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 |
CircularWiringError
|
If circular dependencies detected |
Example
spec = Generator.generate("datetime.datetime now") wired = Wiring(spec)
Accessor Types¶
Accessor¶
Accessor ¶
A callable object that retrieves a wired value.
AioAccessor¶
AioAccessor ¶
Helper for accessing wired objects asynchronously.
__getattr__ ¶
Return an async callable for the named wired object.
Type Aliases¶
Spec¶
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¶
The SpecEntry type represents a single entry in the spec (the configuration for one wired object):
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.
Raised when a circular dependency is detected:
from apywire import CircularWiringError, Wiring
spec = {
"MyClass a": {"dep": "{b}"},
"MyClass b": {"dep": "{a}"},
}
wired = Wiring(spec)
try:
obj = wired.a()
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¶
- Getting Started - Quick start guide
- User Guide - Comprehensive usage documentation
- Examples - Practical examples and patterns