hazrakah#
- class Cached[T](factory, ttl=47.0)#
Bases:
Generic[T]Caches the result of a factory for a configurable TTL.
Invoking a
Cachedinstance via__call__()returns the cached value if the TTL window has not elapsed; otherwise it re-invokes factory and records a fresh expiry timestamp. The factory receives the resolver passed to__call__.- Parameters:
factory (
Callable[[DependencyResolver],T]) – Callable that produces the cached value of typeT; receives the resolver as its first argument.ttl (
float|timedelta) – Time-to-live — acceptsfloat(seconds) ortimedelta(default47.0).
- property ttl: timedelta#
The TTL window as a
timedelta.
- reset() None#
Discard the cached value and its expiration timestamp.
- Return type:
None
- class Container(outer_scope=None, frozen=False, self_resolve=True, namespace=None, autoclose=True, decorators=True)#
Bases:
DependencyRegistry,ScopedDependencyResolver,DependencyResolverA dependency-injection container that supports hierarchical scopes and deterministic destruction.
NOTE: It is NOT necessary to pre-register a type with a Container, hazrakah will resolve any type whether or not it is registered with a Container. The only practical reason to pre-register a type is to assert finer-grained control over instanciation; ie. for specifying lifetime semantics, aliasing types, or to configure a factory function.
Lifetime decorators (
@singleton,@transient,@instanced) are honored lazily: resolving a type with no standing registration registers it with its declared lifetime. A standing registration always takes precedence over decoration metadata. Resolve-time inspection can be turned off withdisable_decorators().Example (Basic)#
container = Container() container.register_transient(Foo) foo = container.resolve(Foo) # supports scopes: scoped_container = container.create_scope() scoped_container.register_transient(Foo) foo = scoped_container.resolve(Foo)
Example (Fluent)#
Registrations return
self, so they can be chained. The following demonstrates this:container = ( Container() .register_decorator(CombinedImpl) # registers both IDatabase & ILogger .register_transient(ConsoleLogger) ) greeter = c.resolve(Greeter)
Example (Context Manager)#
The container can be used as a context manager to create a scoped child container for deterministic cleanup:
container = Container() with container as scoped: scoped.register_transient(Foo) foo = scoped.resolve(Foo) assert foo.is_closed is True # scoped container closes on exit
The returned scope is a child of the parent container, so it inherits registrations from the parent but its tracked instances are isolated:
parent = Container() parent.register_transient(Foo) with parent as child: child.register_transient(Bar) foo = child.resolve(Foo) # inherited from parent bar = child.resolve(Bar) # child-only registration
Example (Async Context Manager)#
The container can also be used as an async context manager. This is recommended when tracked instances expose
async close()methods, as the coroutine is awaited without blocking a running event loop:async with Container() as container: container.register_transient(AioResource) res = container.resolve(AioResource) # res.close() is awaited asynchronously on exit.
Example (Destruction)#
Tracked instances can be destroyed deterministically, without relying on the garbage collector, by calling
dispose(sync) oradispose(async) on the container that tracks them, e.g. a child scope created to serve a single unit of work. Failures in individualclose()calls are observable: a single failure is re-raised as the original exception, and multiple failures are raised as anExceptionGroup.container = Container() container.register_transient(Foo) foo = container.resolve(Foo) container.dispose() # foo.close() is called; failures propagate
async def main() -> None: container = Container() container.register_transient(AioResource) res = container.resolve(AioResource) await container.adispose() # res.close() is awaited
- ivar outer_scope:
The parent container, or
Nonefor the root.- vartype outer_scope:
Optional[Container]
- __enter__() Container#
Create a child scope and return it.
Raises
RuntimeErrorif this Container is already in use as a context manager.- Return type:
- __exit__(exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) None#
Destroy all tracked instances in the context manager scope.
- Parameters:
exc_type (
Optional[type[BaseException]]) – (OPTIONAL) Exception type, if one was raised inside thewithblock.exc_val (
Optional[BaseException]) – (OPTIONAL) The exception instance, if one was raised.exc_tb (
Optional[TracebackType]) – (OPTIONAL) Traceback object, if one was raised.
- Raises:
RuntimeError – If
__exit__is called without a prior__enter__.- Return type:
None
- async __aenter__() Container#
Create a child scope and return it.
Raises
RuntimeErrorif this Container is already in use as an async context manager.- Return type:
- async __aexit__(exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) None#
Async teardown of tracked instances in the context manager scope.
- Parameters:
exc_type (
Optional[type[BaseException]]) – (OPTIONAL) Exception type, if one was raised inside theasync withblock.exc_val (
Optional[BaseException]) – (OPTIONAL) The exception instance, if one was raised.exc_tb (
Optional[TracebackType]) – (OPTIONAL) Traceback object, if one was raised.
- Raises:
RuntimeError – If
__aexit__is called without a prior__aenter__.- Return type:
None
- dispose() None#
Deterministically destroy all instances tracked by this container.
Every tracked instance is attempted in turn: when
autocloseis enabled and the instance exposes aclose()method, it is called, and coroutine results are blocked on and awaited synchronously. A failure in oneclose()call does not stop the remaining tracked instances from being closed, making destruction deterministic. Instances that close successfully are untracked immediately, while instances whoseclose()call fails remain tracked, so a subsequentdisposecall only re-attempts the instances that previously failed. Callingdisposeon a container with nothing left to destroy is a no-op.This method is observable: when exactly one
close()call fails, the original exception is re-raised after all tracked instances have been attempted. When severalclose()calls fail, they are raised together as anExceptionGroup.- Raises:
ExceptionGroup – When multiple tracked instances fail to close.
- Return type:
None
- async adispose() None#
Deterministically destroy all instances tracked by this container, asynchronously.
Equivalent to
dispose(), but coroutineclose()results are awaited natively instead of being blocked on, so a running event loop is never blocked. The same semantics apply: every tracked instance is attempted, instances that close successfully are untracked, instances that fail remain tracked for a subsequent call, a single failure is re-raised as the original exception, and multiple failures are raised together as anExceptionGroup.- Raises:
ExceptionGroup – When multiple tracked instances fail to close.
- Return type:
None
- is_registered(t: Type[Any], namespace: str | Iterable[str | None] | Iterable[str] | None = None) bool#
Check if type t has a registration already.
- Parameters:
t (
Type[Any]) – The type to check for.namespace (
Union[str,Iterable[str|None],Iterable[str],None]) – (Optional) Namespace to check.
- Return type:
bool- Returns:
True if a registration exists.
- register_instance(t: Type[Any] | object, instance: Any | None = None, namespace: str | None = None) Container#
Register a pre-existing instance for type t.
- Parameters:
t (
Union[Type[Any],object]) – The type to bind the instance to.instance (
Optional[Any]) – (OPTIONAL) An object that must be an instance of t. Omit to construct a t instance automatically.namespace (
Optional[str]) – (Optional) Namespace to register into.
- Return type:
- Returns:
selffor method chaining.- Raises:
TypeError – When instance is not an instance of t.
Note on @provides#
The
@providesdecorator on the target type is only discovered when *instance* is omitted (no explicit second argument). In that case, the container discovers__hazrakah_providesmetadata and multi-registers the target under every provided interface.When instance IS provided (explicit registration), @provides metadata on the target class is completely ignored. Only the type specified by t is registered. This applies regardless of whether the concrete class implements additional interfaces via @provides.
- register_singleton(t: Type[Any], target: Any | None = None, namespace: str | None = None) Container#
Create a SINGLETON type registration for type t.
Every resolve of t will result in a single, shared instance of t.
- Parameters:
t (
Type[Any]) – The type to register for.target (
Optional[Any]) – The type or factory to be used when resolving type t. Omit to use t as the target (requires t to be a concrete type.)namespace (
Optional[str]) – (Optional) Namespace to register into.
- Return type:
- Returns:
selffor method chaining.
Note on @provides#
The
@providesdecorator on target is only discovered when *target* is omitted (no explicit second argument). In that case, the container discovers__hazrakah_providesmetadata and multi-registers t under every provided interface.When target IS provided (explicit registration), @provides metadata on the target class is completely ignored. Only the type specified by t is registered. This applies regardless of whether the concrete class implements additional interfaces via @provides.
Examples#
# @provides activates – multi-registers under IFoo, IBar, and MyImpl:
@provides(IFoo, IBar) class MyImpl: … c.register_singleton(MyImpl) # no second arg
# @provides does NOT activate – only IFoo is registered:
c.register_singleton(IFoo, MyImpl) # explicit type override
- register_transient(t: Type[Any], target: Any | None = None, namespace: str | None = None) Container#
Create a TRANSIENT type registration for type t.
Every resolve of t will result in a new instance of t.
- Parameters:
t (
Type[Any]) – The type to register for.target (
Optional[Any]) – The type or factory to be used when resolving type t. Omit to use t as the target (requires t to be a concrete type.)namespace (
Optional[str]) – (Optional) Namespace to register into.
- Return type:
- Returns:
selffor method chaining.
Note on @provides#
The
@providesdecorator on target is only discovered when *target* is omitted (no explicit second argument). In that case, the container discovers__hazrakah_providesmetadata and multi-registers t under every provided interface.When target IS provided (explicit registration), @provides metadata on the target class is completely ignored. Only the type specified by t is registered. This applies regardless of whether the concrete class implements additional interfaces via @provides.
Examples#
# @provides activates – multi-registers under IFoo, IBar, and MyImpl:
@provides(IFoo, IBar) class MyImpl: … c.register_transient(MyImpl) # no second arg
# @provides does NOT activate – only IFoo is registered:
c.register_transient(IFoo, MyImpl) # explicit type override
- resolve(t: Type[T], namespace: str | Iterable[str | None] | Iterable[str] | None = None) T#
Resolve a type to its registered implementation.
For union types (e.g.
IFoo | IBar):If the union is
Optional[T](containsNoneType), unwraps toTand resolves normally; returnsNoneifTis unresolvable.For non-Optional unions (e.g.
IFoo | IBar): finds the single registered implementation among the union members. If multiple distinct targets are registered, raisesResolutionError. Unregistered concrete classes are auto-registered as transient.
For non-union types, looks up the registration and dispatches by lifetime:
INSTANCE- returns the stored instance.SINGLETON- creates or returns a shared instance per container scope.TRANSIENT- creates and returns a new instance each time.
- Return type:
T
- register_decorated(namespace_pattern: str | None = None, class_pattern: str | None = None) Container#
Create registrations based on discovered decorators
@singleton,@transient, and@instanced.This method is not required for decorators to take effect –
resolve()consults decoration metadata lazily for types that have no standing registration. Use this method for eager up-front registration, filtering, ordepends_ontopological ordering.This method is idempotent – repeated calls overwrite registrations (last-in-wins).
- Parameters:
namespace_pattern (
Optional[str]) –A regular expression pattern used to filter which decorated types are registered. The pattern is compiled once and matched against the namespace (i.e.
__module__) of both each entry’s interface type and target callable/class. If either matches, registration proceeds. WhenNone(the default), all decorated types are registered with no filtering.Usage:
# only register types defined in the "myapp.services" module tree container.register_decorated(namespace_pattern=r"myapp\.services\..*")
class_pattern (
Optional[str]) – A regular expression pattern used to filter by class name (i.e.__qualname__) of each entry’s interface and target. If either matches, registration proceeds for that info. WhenNone(the default), no class-name filtering is applied.
- Return type:
- Returns:
selffor method chaining.
- invoke(target: Callable[[...], Any], namespace: str | None = None, **kwargs: Any) Any | None#
Invoke a callable with dependency injection for each unsupplied parameter.
Resolves each parameter of target via
resolve, unless the parameter name is already supplied viakwargs. Parameters without type annotations raiseTypeError. Resolution failures fall back to the parameter’s default value; if no default exists the exception propagates unchanged.- Parameters:
target (
Callable[...,Any]) – A callable whose parameters should be resolved via DI.namespace (
str|None) – (Optional) Namespace to use forresolvecalls.kwargs (
Any) – Override values for individual parameters by name.
- Return type:
Any|None- Returns:
The result returned by target.
- Raises:
TypeError – If a parameter is missing a type annotation.
ResolutionError – If a required parameter cannot be resolved and has no default.
- create_scope(frozen: bool | None = None, self_resolve: bool | None = None, namespace: str | None = None, autoclose: bool | None = None, decorators: bool | None = None) Container#
Create a new scope as a
Containerinstance.
- disable_decorators() Container#
Disable resolve-time inspection of lifetime-decorator metadata on this container.
Once disabled,
resolve()no longer consults@singleton/@transient/@instancedmetadata for types without a standing registration – unadorned behavior resumes (concrete types auto-register as transient). Existing registrations are unaffected, and eagerregister_decorated()still works.The flag propagates to containers created via
create_scope(); a child may override it withcreate_scope(decorators=True).c = Container().disable_decorators() @singleton class Foo: ... c.resolve(Foo) is c.resolve(Foo) # False -- plain transient fallback
- Return type:
- Returns:
selffor method chaining.
- freeze() None#
Freeze the Container.
Any attempt to create registrations after the container has been frozen will result in a
RegistrationError.- Return type:
None
- dispose() None#
Deterministically destroy all instances tracked by this container.
Every tracked instance is attempted in turn: when
autocloseis enabled and the instance exposes aclose()method, it is called, and coroutine results are blocked on and awaited synchronously. A failure in oneclose()call does not stop the remaining tracked instances from being closed, making destruction deterministic. Instances that close successfully are untracked immediately, while instances whoseclose()call fails remain tracked, so a subsequentdisposecall only re-attempts the instances that previously failed. Callingdisposeon a container with nothing left to destroy is a no-op.This method is observable: when exactly one
close()call fails, the original exception is re-raised after all tracked instances have been attempted. When severalclose()calls fail, they are raised together as anExceptionGroup.- Raises:
ExceptionGroup – When multiple tracked instances fail to close.
- Return type:
None
- async adispose() None#
Deterministically destroy all instances tracked by this container, asynchronously.
Equivalent to
dispose(), but coroutineclose()results are awaited natively instead of being blocked on, so a running event loop is never blocked. The same semantics apply: every tracked instance is attempted, instances that close successfully are untracked, instances that fail remain tracked for a subsequent call, a single failure is re-raised as the original exception, and multiple failures are raised together as anExceptionGroup.- Raises:
ExceptionGroup – When multiple tracked instances fail to close.
- Return type:
None
- class DependencyRegistry(*args, **kwargs)#
Bases:
DependencyResolver,ProtocolA protocol for dependency registration (and resolution) tasks.
- is_registered(t: Type[Any], namespace: str | None = None) bool#
Check if type t has a registration already.
- Parameters:
t (
Type[Any]) – The type to check for.namespace (
Optional[str]) – (Optional) Namespace to check.
- Return type:
bool- Returns:
True if a registration exists.
- register_instance(t: Type[Any], instance: Any, namespace: str | None = None) DependencyRegistry#
Create an INSTANCE type registration for type t.
Every resolve of t will result in the specified object instance.
- Parameters:
t (
Type[Any]) – The type to register for.instance (
Any) – The instance to register.namespace (
Optional[str]) – (Optional) Namespace to register in.
- Return type:
- Returns:
selffor method chaining (onContainerimplementations).- Raises:
TypeError – When the provided instance is not an instance of type t (type mismatch.)
- register_singleton(t: Type[Any], target: Any | None = None, namespace: str | None = None) DependencyRegistry#
Create a SINGLETON type registration for type t.
Every resolve of t will result in a single, shared instance of t.
- Parameters:
t (
Type[Any]) – The type to register for.target (
Optional[Any]) – The type or factory to be used when resolving type t. Omit to use t as the target (requires t to be a concrete type.)namespace (
Optional[str]) – (Optional) Namespace to register in.
- Return type:
- Returns:
selffor method chaining (onContainerimplementations).
- register_transient(t: Type[Any], target: Any | None = None, namespace: str | None = None) DependencyRegistry#
Create a TRANSIENT type registration for type t.
Every resolve of t will result in a new instance of t.
- Parameters:
t (
Type[Any]) – The type to register for.target (
Optional[Any]) – The type or factory to be used when resolving type t. Omit to use t as the target (requires t to be a concrete type.)namespace (
Optional[str]) – (Optional) Namespace to register in.
- Return type:
- Returns:
selffor method chaining (onContainerimplementations).
- class DependencyResolver(*args, **kwargs)#
Bases:
ProtocolA protocol for dependency resolution without exposing registration methods.
- resolve(t: Type[T], namespace: str | Iterable[str | None] | Iterable[str] | None = None) T#
Resolve type t using available registrations.
- Parameters:
t (
Type[T]) – The type to resolve.namespace (
Union[str,Iterable[str|None],Iterable[str],None]) – (Optional) Namespace resolution priority chain.
- Raises:
KeyError – When type t is not a concrete class and has no registration.
RuntimeError – When a registration is malformed.
- Return type:
T- Returns:
The object instance resolved for type t.
- exception ResolutionError(message, *, cause=None, matched=None)#
Bases:
KeyErrorRaised when a type cannot be resolved.
Typical situations that trigger this error:
No registration found for a concrete or abstract type during
resolve().Multiple registrations for different implementations of a union type alias, making the target ambiguous (e.g.
IFoo | IBarwhere both are registered to different targets).
The
matchedattribute contains all pre-deduplication matches when available, allowing callers to inspect which types were considered during resolution.Create the exception.
- Parameters:
message (
str) – Human-readable description of the problem.cause (
BaseException|None) – Optional original exception that led to this error. It is stored as__cause__so that traceback chaining works automatically.matched (
list[tuple[Type[Any],Any,Lifetime,Any]] |None) – Pre-deduplication list of (type, scope, lifetime, registration) tuples for all matches found during resolution.
- exception RegistrationError(message, *, cause=None)#
Bases:
RuntimeErrorRaised when a registration cannot be processed.
Typical situations that trigger this error:
Attempting to create an instance from a registration that has no
target(e.g. aLifetime.INSTANCEregistration without an associated object).Supplying a factory that does not conform to the expected signature
Callable[[Container], T].Providing an instance to
Container.register_instance()that is not an instance of the registration type.
Create the exception.
- Parameters:
message (
str) – Human-readable description of the problem.cause (
BaseException|None) – Optional original exception that led to this error. It is stored as__cause__so that traceback chaining works automatically.
- class ScopedDependencyResolver(*args, **kwargs)#
Bases:
DependencyResolver,Protocol- create_scope(frozen=None, self_resolve=None, namespace=None)#
Create a new scope as a
Containerinstance.- Parameters:
frozen (
bool|None) – (Optional) Freezes the new scope.self_resolve (
bool|None) – (Optional) Enable self-resolve.namespace (
str|None) – (Optional) Associative namespace string.
- Return type:
- Returns:
A
Containerinstance to use for the the scope.
- provides(*types, namespace=None)#
Passive marker decorator: declares which protocols cls implements.
Stores metadata on the decorated class via
__hazrakah_provides; zero registration logic at decoration time. Activation depends on how the container registers the class:No explicit type arg on register_* –> @provides triggers multi-registration.
Explicit type arg on register_* –> @provides is ignored.
Usage:
@provides(IFoo, IBar) # stores metadata only class MyClass: ... c.register_singleton(MyClass) # activates: registers IFoo, IBar, MyClass c.register_transient(IBaz, ...) # ignores @provides on other classes @provides() # marker-only, no interfaces (backward compatible)
- Parameters:
types (
Type[Any]) – Protocol types the decorated class implements. Variadic – no tuple wrapping.namespace (
Optional[str]) – (Optional) Namespace to register into.
- Return type:
Callable[[T],T]
- singleton(target=None, *, types=None, depends_on=(), namespace=None)#
Register target as a singleton.
Usage:
@singleton → self-as (classes only) @singleton(types=IFoo) → explicit interface @singleton(types=(IFoo, IBar)) → multiple interfaces
- Raises:
RegistrationError – If target is already decorated with
@provides— the two decorators are incompatible.- Return type:
Any
- transient(target=None, *, types=None, depends_on=(), namespace=None)#
Register target as a transient.
- Return type:
Any
- instanced(target=None, *, types=None, depends_on=(), namespace=None)#
Register target as an instance (created once at decoration time).
- Return type:
Any