Skip to content

xtr_dependency_injection

A bundle and kernel layer for the xtr libraries, built on wireup.

Each library ships one bundle; an application lists the bundles it wants in its config/bundles.py — installing a package activates nothing — and the peers a bundle requires arrive through @required_bundle. What comes out is a plain wireup AsyncContainer: this package decides what goes into it, in which order, for which environment, and runs the lifecycle around it.

UNIT_PARTICIPANT_TAG module-attribute

UNIT_PARTICIPANT_TAG: Final = 'kernel.unit_participant'

The tag a unit participant carries; an optional priority attribute, higher told first.

Injected module-attribute

Injected: TypeAlias = Annotated[T, Autowire()]

Mark a parameter as container-provided, resolved by its type.

Alias of :data:Annotated[T, Autowire()] <Autowire> — the default autowiring, resolved by the parameter's type annotation.

BUNDLE_PASS_PRIORITY module-attribute

BUNDLE_PASS_PRIORITY: Final = -10000

Where a bundle overriding process runs: last in BEFORE_OPTIMIZATION.

The later stages still run after it.

DEFAULT_EXCLUDES module-attribute

DEFAULT_EXCLUDES: Final[tuple[str, ...]] = ('*.tests', '*.tests.*', '*.test_*', '*.conftest', '*.__main__')

fnmatch patterns of module names never imported by a scan.

Tests and entry points are not services, and importing __main__ would run the application. Kernel(exclude=...) adds to these; Kernel(default_excludes=False) drops them.

ServiceKey

ServiceKey = tuple[type, Hashable | None]

(provided type, qualifier) — the identity wireup registers a service under.

Decorates dataclass

Decorates(key: ServiceKey, priority: int = 0, on_invalid: OnInvalid = OnInvalid.EXCEPTION)

What Definition.set_decorated_service records: a target key, priority and on-invalid.

Recorded by :meth:Definition.set_decorated_service.

Attributes:

  • key (ServiceKey) –

    The (type, qualifier) of the decorated service.

  • priority (int) –

    The decoration's priority. Higher wraps first.

  • on_invalid (OnInvalid) –

    Behavior when the target is not defined - :class:~xtr_dependency_injection.decorator.as_decorator.OnInvalid.

Definition dataclass

Definition(key: ServiceKey, provider: object, kind: Literal['class', 'factory', 'instance'], lifetime: Lifetime, origin: Origin, priority: int | None = None, tags: dict[str, list[dict[str, object]]] = dict(), decorates: Decorates | None = None, before: tuple[type, ...] = (), after: tuple[type, ...] = (), arguments: dict[str, object] = dict(), lifetime_explicit: bool = False)

One service as the builder knows it, before it is compiled for wireup.

Attributes:

  • key (ServiceKey) –

    The type and qualifier it is provided under.

  • provider (object) –

    The class, factory function or instance that builds it.

  • kind (Literal['class', 'factory', 'instance']) –

    How provider is registered: "class", "factory" or "instance".

  • lifetime (Lifetime) –

    How long wireup keeps what it builds.

  • origin (Origin) –

    Who contributed it.

  • priority (int | None) –

    Its position in ordered collections; None means "no explicit priority", read as zero by :func:emission_order and consumed by :func:sort_with_priorities.

  • tags (dict[str, list[dict[str, object]]]) –

    Tag name → list of attribute mappings. kernel.reset is the tag resettable services carry, read by the compiler.

  • decorates (Decorates | None) –

    What service this definition decorates, when it does.

  • before (tuple[type, ...]) –

    Types this definition must precede in tagged collections (consumed by :func:sort_with_priorities).

  • after (tuple[type, ...]) –

    Types this definition must follow in tagged collections.

  • arguments (dict[str, object]) –

    Values for the provider's parameters, by name, given instead of injecting them. A value may hold an env() placeholder or a %name% reference: it is resolved when the service is built.

  • lifetime_explicit (bool) –

    Whether lifetime was asked for rather than left to its default — an autoconfiguration rule never overrides one that was.

set_argument

set_argument(name: str, value: object) -> Definition

Give the provider's parameter name the value value instead of injecting it.

This is how a bundle hands its config to a service: the value stays on the definition, so an env() placeholder in it is resolved when the service is built, and the report shows it.

set_arguments

set_arguments(arguments: Mapping[str, object]) -> Definition

Replace every argument by arguments.

get_arguments

get_arguments() -> dict[str, object]

Return the arguments, by parameter name.

add_tag

add_tag(name: str, /, **attributes: object) -> Definition

Add a tag name with the given attribute mapping.

Repeatable — each call appends one attribute mapping under name.

has_tag

has_tag(name: str) -> bool

Return whether the tag name was added at least once.

get_tag

get_tag(name: str) -> list[dict[str, object]]

Return every attribute mapping added under name.

Returns an empty list when the tag was never added.

clear_tag

clear_tag(name: str) -> Definition

Remove every attribute mapping added under name.

set_decorated_service

set_decorated_service(target: type, /, *, qualifier: Hashable | None = None, priority: int = 0, on_invalid: OnInvalid = OnInvalid.EXCEPTION) -> Definition

Mark this definition as decorating (target, qualifier).

on_invalid chooses what happens when the target is not defined - see :class:~xtr_dependency_injection.decorator.as_decorator.OnInvalid.

Origin dataclass

Origin(kind: Literal['kernel', 'bundle', 'app'], name: str, note: str | None = None)

Who contributed a definition: the kernel, a bundle, or the application.

Attributes:

  • kind (Literal['kernel', 'bundle', 'app']) –

    "kernel", "bundle" or "app".

  • name (str) –

    The bundle's name, or module:qualname of the application object.

  • note (str | None) –

    How it got there, when not directly — e.g. "via autoconfigure of app.x:Y".

ContainerBuilder

ContainerBuilder(state: BuildState, origin: Origin)

A whole-container view for a bundle or a compiler pass.

In phase build, only parameter reads/writes, container queries, :meth:register_for_autoconfiguration and :meth:register_attribute_for_autoconfiguration are allowed. In phase prepend, additionally :meth:prepend_extension_config. In phase load and process, definition/alias/tag mutations too. See the module docstring for the full phase → allowed-operations table.

Bind this builder to state as origin.

has

has(service: type, /, qualifier: Hashable | None = None) -> bool

Return whether a definition or alias exists for (service, qualifier).

register

register(service: type, /, *, qualifier: Hashable | None = None, lifetime: Lifetime | None = None) -> Definition

Register service as a class definition and return it, for further mutation.

lifetime is "singleton" when not given, and then left for autoconfiguration to set. Allowed in phases load and process.

set_definition

set_definition(definition: Definition) -> Definition

Overwrite the definition of definition.key with definition.

Allowed in phases load and process. Records the previous origin as an override.

get_definition

get_definition(service: type, /, qualifier: Hashable | None = None) -> Definition

Return the definition of (service, qualifier).

Raises:

has_definition

has_definition(service: type, /, qualifier: Hashable | None = None) -> bool

Return whether the definition of (service, qualifier) exists.

Unlike :meth:has, this does not follow aliases.

find_definition

find_definition(service: type, /, qualifier: Hashable | None = None) -> Definition

Return the definition (service, qualifier) resolves to, following aliases.

Raises:

remove_definition

remove_definition(service: type, /, qualifier: Hashable | None = None) -> None

Remove the definition of (service, qualifier).

Raises:

get_definitions

get_definitions() -> tuple[Definition, ...]

Return every definition, in declaration order.

set_alias

set_alias(alias: type, target: type, /, *, alias_qualifier: Hashable | None = None, target_qualifier: Hashable | None = None) -> None

Register an alias from (alias, alias_qualifier) to (target, target_qualifier).

Allowed in phases load and process.

get_aliases

get_aliases() -> dict[ServiceKey, ServiceKey]

Return every alias, alias_key -> target_key, in declaration order.

get_alias

get_alias(alias: type, /, qualifier: Hashable | None = None) -> ServiceKey

Return the target key for (alias, qualifier).

Raises:

has_alias

has_alias(alias: type, /, qualifier: Hashable | None = None) -> bool

Return whether (alias, qualifier) is aliased to another key.

remove_alias

remove_alias(alias: type, /, qualifier: Hashable | None = None) -> None

Remove the alias (alias, qualifier).

Raises:

find_tagged_service_ids

find_tagged_service_ids(tag: str) -> dict[ServiceKey, list[dict[str, object]]]

Return every definition tagged tag, mapped to its attribute list.

Definition order.

add_compiler_pass

add_compiler_pass(compiler_pass: CompilerPassInterface, /, *, stage: PassStage = PassStage.BEFORE_OPTIMIZATION, priority: int = 0) -> None

Register compiler_pass to run in stage at priority.

Only allowed in phase build (from :meth:Bundle.build). The pass runs with a builder bound to this builder's origin.

Raises:

  • TypeError –

    If compiler_pass does not implement :class:CompilerPassInterface.

get_compiler

get_compiler() -> Compiler

Return the compiler: its pass config and its log.

log

log(compiler_pass: CompilerPassInterface, message: str) -> None

Record message in the compiler log, under compiler_pass.

register_for_autoconfiguration

register_for_autoconfiguration(type_: type) -> AutoconfigureRule

Return an :class:AutoconfigureRule for every subclass of type_.

Allowed in phases build and load. ResolveInstanceofConditionalsPass applies each rule to every non-kernel definition whose built type has type_ in its __mro__ (a nominal subclass check). A tag already carried on a definition wins over the rule's — explicit stays.

register_attribute_for_autoconfiguration

register_attribute_for_autoconfiguration(reader: Reader, callback: Apply) -> None

Register a callback called for every metadata item reader finds on a candidate.

AttributeAutoconfigurationPass runs the callback with the registering bundle's :class:ServiceConfigurator.

set_parameter

set_parameter(name: str, value: object) -> None

Set the parameter name to value.

Merges into the parameter sources under this builder's origin; a leaf set twice by non-app sources with a different value raises :class:ParameterConflictError at parameter-merge time.

Raises:

  • BuilderPhaseError –

    Once the OPTIMIZE stage has resolved the parameters' %name% references — a parameter set later would keep its own unresolved. Set it from a pass that runs BEFORE_OPTIMIZATION.

get_extension_config

get_extension_config(bundle: str) -> object
get_extension_config(bundle: type[C]) -> C
get_extension_config(bundle: str | type[C]) -> object

Return the resolved config of a bundle, by name or by config type.

Raises:

prepend_extension_config

prepend_extension_config(bundle: str | type[C], transform: Callable[[C], C]) -> None

Adjust another bundle's config, before it is loaded.

Only allowed in phase prepend (from :meth:Bundle.prepend_extension).

Raises:

  • ConfigProviderError –

    If bundle is a type owned by no known bundle, or if the target takes no config.

get_parameter

get_parameter(name: str) -> object

Return the build-time parameter name (dotted path).

Allowed from phase build onward.

Raises:

  • ParameterNotFoundError –

    If the parameter is not set.

has_parameter

has_parameter(name: str) -> bool

Return whether the parameter name is defined.

Allowed from phase build onward.

get_parameter_bag

get_parameter_bag() -> EnvPlaceholderParameterBag

Return the parameters of the build, merged, as stored.

%name% references are resolved by ResolveParameterPlaceHoldersPass.

ServiceConfigurator

ServiceConfigurator(state: BuildState, origin: Origin)

Defines services on behalf of one bundle.

set, instance, alias and load cover every way a bundle contributes a service from load_extension.

Define services into state, as origin.

instance

instance(obj: object, /, *, qualifier: Hashable | None = None) -> Definition

Provide obj itself, under its own type.

The key is always (type(obj), qualifier). Register an alias to expose it under an interface (:meth:alias).

set

set(target: type | Callable[..., object], /, *, qualifier: Hashable | None = None, lifetime: Lifetime | None = None) -> Definition

Register target — a class or a factory function — as a service.

lifetime is "singleton" when not given, and then left for autoconfiguration to set.

A class is registered under its own type; a function under its evaluated return type. Same key + same provider is a no-op.

Raises:

  • InvalidArgumentTypeError –

    If target is not a class or a plain function, or is a function that does not annotate its return type.

alias

alias(alias: type, target: type, /, *, alias_qualifier: Hashable | None = None, target_qualifier: Hashable | None = None) -> None

Register an alias from (alias, alias_qualifier) to (target, target_qualifier).

The alias target is validated at compile time (missing → UnknownServiceError).

load

load(*resources: str | ModuleType) -> None

Scan resources too, once every bundle has loaded, as this bundle's.

This is how a bundle scans a module only when a peer is active.

Bundle

Base class of every bundle; declare one with @as_bundle.

A bundle is built with no arguments — discovery builds it that way — and its hooks run in dependency order: build and prepend_extension while the container is being wired, load_extension while services are defined, process once every bundle loaded, boot and shutdown around the container's life.

Attributes:

  • container (ContainerInterface | None) –

    The container the bundle has been booted against, set by the kernel right before :meth:boot runs. It is None outside a boot/shutdown cycle.

build

build(builder: ContainerBuilder) -> None

Wire the container at compile time. Does nothing by default.

Runs once per build, in bundle order, before any bundle's prepend_extension. Register compiler passes or autoconfiguration rules here.

prepend_extension

prepend_extension(builder: ContainerBuilder) -> None

Adjust other bundles' configs before they are loaded. Does nothing by default.

Call builder.prepend_extension_config(target, transform) for every adjustment.

load_extension

load_extension(config: ConfigT, services: ServiceConfigurator, builder: ContainerBuilder) -> None

Define this bundle's services from its resolved config. Does nothing by default.

process

process(builder: ContainerBuilder) -> None

Inspect and adjust every definition, from every bundle. Does nothing by default.

boot async

boot() -> None

Run once the container is built, before the application. Does nothing by default.

self.container is set by the kernel right before this runs. Fail here, not on first use: bind handlers and check signatures now when that is cheap.

shutdown async

shutdown() -> None

Run as the kernel shuts down, before the container closes. Does nothing by default.

metadata classmethod

metadata() -> BundleMetadata

Return the metadata @as_bundle and @required_bundle recorded on this class.

@required_bundle declarations are merged in at call time so their source order relative to @as_bundle does not matter.

Raises:

  • BundleDefinitionError –

    If the class was not decorated; a subclass of a decorated bundle is a different bundle and needs its own.

BundleMetadata dataclass

BundleMetadata(name: str, config: type[object], resources: tuple[str, ...] = (), required: tuple[RequiredBundle, ...] = tuple())

A bundle's declaration, as @as_bundle and @required_bundle recorded it.

Attributes:

  • name (str) –

    The name the bundle is known by everywhere.

  • config (type[object]) –

    Its config type; NoConfig when it takes none.

  • resources (tuple[str, ...]) –

    Modules and packages scanned like the application's.

  • required (tuple[RequiredBundle, ...]) –

    The peer bundles it depends on, in decoration order.

NoConfig dataclass

NoConfig()

The config of a bundle that takes none. Never registered, never configurable.

RequiredBundle dataclass

RequiredBundle(target: str | type[AnyBundle], ignore_on_invalid: bool = False)

One @required_bundle declaration on a bundle class.

Attributes:

  • target (str | type[AnyBundle]) –

    The peer's class, or "module:Class" for lazy import.

  • ignore_on_invalid (bool) –

    When the string target cannot be imported, the resolver reports it as skipped instead of raising.

CacheClearerInterface

Bases: Protocol

Empties a cache that removing the cache directory does not reach.

A cache kept elsewhere — on a server, in a directory of its own — survives the cache directory being removed. A service implementing this interface is autoconfigured with the kernel.cache_clearer tag, and the kernel's :class:~xtr_dependency_injection.cache_clearer.ChainCacheClearer runs it.

clear async

clear(cache_dir: Path) -> None

Empty the cache.

Parameters:

  • cache_dir (Path) –

    The cache directory being cleared.

ChainCacheClearer

ChainCacheClearer(clearers: Iterable[CacheClearerInterface] = ())

Bases: CacheClearerInterface

Runs several cache clearers in order, as a single one.

Run clearers, in the order given.

clear async

clear(cache_dir: Path) -> None

Run every clearer, one after another, in order.

CacheWarmer

Bases: CacheWarmerInterface, ABC

A cache warmer that knows how to write a file into the cache.

A subclass implements :meth:warm_up and :meth:is_optional, and writes each file it produces through :meth:_write_cache_file.

CacheWarmerAggregate

CacheWarmerAggregate(warmers: Iterable[CacheWarmerInterface] = ())

Bases: CacheWarmerInterface

Runs several cache warmers in order, as a single one.

Only the warmers that are not optional run, until :meth:enable_optional_warmers lets the optional ones run too; :meth:enable_only_optional_warmers runs nothing but those.

Run warmers, in the order given.

enable_optional_warmers

enable_optional_warmers() -> None

Run the optional warmers too.

enable_only_optional_warmers

enable_only_optional_warmers() -> None

Run the optional warmers, and none of the others.

warm_up async

warm_up(cache_dir: Path, build_dir: Path | None = None) -> None

Run every enabled warmer, one after another, in order.

is_optional

is_optional() -> bool

Never: the aggregate is what runs the warmers that are not optional either.

CacheWarmerInterface

Bases: WarmableInterface, Protocol

Fills one part of the application's cache.

A service implementing this interface is autoconfigured with the kernel.cache_warmer tag, and the kernel's :class:~xtr_dependency_injection.cache_warmer.CacheWarmerAggregate runs it. One that is not optional runs when the kernel boots with a cold cache; every one runs on cache:warmup and cache:clear.

is_optional

is_optional() -> bool

Tell whether this warmer may be skipped.

A warmer whose cache the application can also fill bit by bit, the first time each piece is needed, is optional: skipping it costs a slower first use, never a wrong answer. One whose cache the application cannot do without is not.

WarmableInterface

Bases: Protocol

Fills its cache on demand, so the first use does not pay for it.

warm_up async

warm_up(cache_dir: Path, build_dir: Path | None = None) -> None

Fill the cache.

Parameters:

  • cache_dir (Path) –

    Where what is written at run time goes; the application may write there again later.

  • build_dir (Path | None, default: None ) –

    Where what is only ever read goes, so a deploy can ship it on a read-only filesystem; often cache_dir itself. None when the caller gives no such place: write only to cache_dir then.

WarmedCache

WarmedCache(cache_dir: Path, fingerprint: str)

Records, in the cache directory, which build its warmers last filled it for.

The kernel warms the cache when it boots only while the directory is not fresh — it holds no stamp, or one written for another build — so every later start skips the warm-up. cache:clear removes the directory, and with it the stamp, so the next start warms again.

A build is told apart by its fingerprint: whatever, when it changes, makes what the warmers wrote stale.

Keep the stamp in cache_dir, for the build fingerprint names.

is_fresh

is_fresh() -> bool

Tell whether the warmers already filled the cache directory for this build.

mark_fresh

mark_fresh() -> None

Record that the warmers filled the cache directory for this build.

The stamp is replaced in one step, so a process reading it meanwhile sees the old one or the new one.

lock async

lock() -> AsyncGenerator[None]

Hold the cache directory, creating it, so one process at a time warms it.

The lock is a file lock: it holds across processes, and is let go whatever happens, even when the process dies. Where file locks are not available it holds nothing.

Waiting never blocks the event loop: the lock is tried without blocking, and between tries the task sleeps, so the wait can be cancelled.

CompilerPassInterface

Bases: Protocol

A step of the compilation that sees, and may change, every definition.

A pass is registered with a stage and a priority — through ContainerBuilder.add_compiler_pass from a bundle's build, or @compiler_pass on a scanned class — and the compiler hands it a :class:ContainerBuilder bound to whoever registered it, so what the pass defines carries that origin. A bundle overriding process is itself a pass.

process

process(builder: ContainerBuilder) -> None

Inspect and adjust the container being built.

PassStage

Bases: Enum

The order the stages execute in.

AliasOf dataclass

AliasOf(bundle: str)

Mark a config field as forwarding its value to another bundle's config.

Attributes:

  • bundle (str) –

    The name of the target bundle receiving the value.

Autowire dataclass

Autowire(param: str | None = None, env: str | None = None, **fastapi: object)

Bases: DependencyBase

Mark a parameter as container-provided — by type, by parameter, or from the environment.

Without :attr:param or :attr:env, the parameter is resolved by its type, like :data:Injected. With :attr:param, the named dotted parameter (such as kernel.name) is injected, any environment placeholder in it resolved. With :attr:env, the environment variable expression ("int:PORT", "json:file:SECRETS") is read when the service is built, through the container's processors.

When the web framework is installed the marker is also one of its dependency declarations, so the same annotation resolves through the container inside a route; **fastapi exists for the framework's own copy of a marker and is never written by hand.

Attributes:

  • param (str | None) –

    A dotted parameter name to inject.

  • env (str | None) –

    An environment variable expression to inject.

Raises:

  • ValueError –

    If both :attr:param and :attr:env are given.

Record what to inject; refuse naming both a parameter and a variable.

AutowireDecorated dataclass

AutowireDecorated()

Marks the parameter of a decorator that receives the decorated service.

Applied through Annotated[T, AutowireDecorated()] to the parameter that receives the service the decorator wraps.

OnInvalid

Bases: Enum

What a decorator does when the decorated service is not defined.

:attr:EXCEPTION fails the build, :attr:IGNORE drops the decorator, and :attr:NULL keeps it under the target key with None for its inner parameter.

EXCEPTION class-attribute instance-attribute

EXCEPTION = 'exception'

Fail the build with :class:UnknownServiceError (the default).

IGNORE class-attribute instance-attribute

IGNORE = 'ignore'

Drop the decorator - it never enters the container.

NULL class-attribute instance-attribute

NULL = 'null'

Keep the decorator under the target key; feed None to its inner parameter.

Target dataclass

Target(name: Hashable, **fastapi: object)

Bases: DependencyBase

Point a container-provided parameter at a specific qualifier.

Names the qualifier the container should resolve for this parameter, when several services of one type live under different qualifiers::

def __init__(self, mailer: Annotated[Mailer, Target("smtp")]) -> None: ...

On its own it marks the parameter as container-provided — no Autowire() needed beside it, though Annotated[T, Autowire(), Target("smtp")] means the same. It cannot sit beside Autowire(param=...) or Autowire(env=...): a parameter is a parameter, an environment variable, or a qualified service.

When the web framework is installed the marker is also one of its dependency declarations, so the same annotation resolves through the container inside a route; **fastapi exists for the framework's own copy of a marker and is never written by hand.

Attributes:

  • name (Hashable) –

    The qualifier of the service to inject.

Record the qualifier the container resolves for this parameter.

KernelReport dataclass

KernelReport(bundles: tuple[BundleReport, ...] = (), configs: tuple[ConfigReport, ...] = (), definitions: tuple[DefinitionReport, ...] = (), scan: ScanReport = ScanReport())

Everything one build decided, frozen when its container is compiled.

render

render(section: Section | None = None) -> str

Return the report as plain-text tables: one section, or all of them.

Fixed columns, no colours, nothing but the standard library — so the same text serves a terminal, a log line and an exception note.

FastapiIntegrationError

FastapiIntegrationError(reason: str)

Bases: DependencyInjectionError

The web integration cannot serve a request from the container.

Raised when a resolver runs with no attached kernel or no open request scope, and when a second kernel is attached to an application one already serves.

Attributes:

  • reason (str) –

    What the integration is missing.

Record what the integration is missing.

BootedKernel

BootedKernel(container: AsyncContainer, kernel: KernelInterface, bundles: Sequence[AnyBundle], on_shutdown: Sequence[Callable[..., object]])

A booted kernel: its container, and the shutdown that releases it.

Use it as an async context manager, which shuts it down on exit::

async with await kernel.boot() as booted:
    bus = await booted.container.get(MessageBusInterface)

Hold what shutdown needs: the booted bundles and the application's hooks.

shutdown async

shutdown() -> None

Run the application's @on_shutdown hooks, then every bundle's, then close.

Once the hooks ran — they are what stops a worker or a scheduler the application started, and with it whatever keeps opening units — every unit of work still open, a request in flight, a message being handled, is waited for, up to thirty seconds: its scoped services use what the bundles and the container are about to close. Past that the kernel closes anyway, logging how many were left open. Once shut down, its container refuses to resolve.

Bundles shut down in reverse order, and the container is closed last — running every generator factory's cleanup. No step stops the others: once every one ran, the first BaseException (a cancellation, an interrupt) propagates as it arrived; otherwise every Exception is raised together. A second call does nothing.

Raises:

  • ExceptionGroup –

    If a step raised an Exception, and none a BaseException.

CompiledKernel

CompiledKernel(container: AsyncContainer, report: KernelReport, *, info: KernelInterface, bundles: Sequence[AnyBundle], on_boot: Sequence[Callable[..., object]], on_shutdown: Sequence[Callable[..., object]])

A compiled kernel: its container and report, ready to boot once.

The container exists already, so a framework integration can be wired before the application starts; lifespan then boots and shuts down around the application's life. Framework integrations that need the engine container use engine_container(compiled) from xtr_dependency_injection.integration.wireup.

Hold the container and everything boot and shutdown run.

boot async

boot() -> BootedKernel

Boot every bundle in order, then run the application's @on_boot hooks.

If a step raises, what already booted is shut down in reverse, the container is closed, and the error propagates — carrying a note when that rollback failed too, so the first failure stays the one raised.

Raises:

lifespan

lifespan(app: object) -> AbstractAsyncContextManager[None]

Return an ASGI-style lifespan: boot on enter, shut down on exit.

Kernel

Kernel(package: str | ModuleType | None, /, *, env: str | None = None, debug: bool | None = None, name: str | None = None, bundles: Mapping[type[AnyBundle], Mapping[str, bool]] | None = None, resources: Sequence[str] | None = None, exclude: Sequence[str] = (), default_excludes: bool = True, allowed_envs: Sequence[str] | None = None, concurrent_scoped_access: bool = True, environ: Mapping[str, str] | None = None)

An application's kernel: which bundles, which resources, which environment.

Constructing one stores its arguments and nothing else; build, boot and run do the work, each time afresh.

Store the kernel's recipe.

Parameters:

  • package (str | ModuleType | None) –

    The application package, scanned recursively: its dotted name or the module. Kernel(__package__) in the package's own kernel.py names it once, where it cannot drift.

  • env (str | None, default: None ) –

    The environment; default APP_ENV, else "dev".

  • debug (bool | None, default: None ) –

    Debug mode; default APP_DEBUG, else true for "dev" and "test".

  • name (str | None, default: None ) –

    The application's name; default the package's last component.

  • bundles (Mapping[type[AnyBundle], Mapping[str, bool]] | None, default: None ) –

    The bundle classes the application lists, mapped to their per-environment activity flags ({"all": True} or {"dev": True}). When None the kernel imports <package>.config.bundles — or <package>.bundles when that is absent — and reads its BUNDLES mapping. A class that list imports from a package that is not installed is stood in for, and reported disabled where its flags leave it inactive.

  • resources (Sequence[str] | None, default: None ) –

    What to scan instead of package.

  • exclude (Sequence[str], default: () ) –

    fnmatch patterns of modules never scanned, added to DEFAULT_EXCLUDES. A pattern starting with . is relative to the application package — ".scripts" is "<package>.scripts" — whatever resources names.

  • default_excludes (bool, default: True ) –

    Whether DEFAULT_EXCLUDES applies; false leaves exclude alone.

  • allowed_envs (Sequence[str] | None, default: None ) –

    The only environments the kernel accepts, and the only names a folder under config/packages/ or config/routes/ may take.

  • concurrent_scoped_access (bool, default: True ) –

    Whether a scoped service is built under a lock, so tasks of one unit of work asking for it together get the one instance; False drops the lock, for a unit only ever used by one task at a time.

  • environ (Mapping[str, str] | None, default: None ) –

    Where APP_ENV, APP_DEBUG and every env(...) placeholder are read; None reads the live process environment. A test gives each kernel its own.

Raises:

  • InvalidArgumentError –

    If package is None or empty — what __package__ is in a script run on its own, outside any package.

name property

name: str

The application's name.

package property

package: str

The application package, dotted.

environment property

environment: str

The environment: the argument, else APP_ENV, else "dev".

debug property

debug: bool

Debug mode: the argument, else APP_DEBUG, else true for "dev" and "test".

Any other environment fails closed — debug is off — so a security-relevant flag never defaults to on for a name the kernel does not know. "prod" is off silently; an environment outside "dev", "test" and "prod" warns once per process, saying how to ask for debug explicitly.

Raises:

project_dir property

project_dir: Path

The nearest directory above the package with a pyproject.toml; else the package's.

with_env

with_env(env: str, /, *, debug: bool | None = None) -> Kernel

Return the same recipe for another environment.

An explicit debug carries over unless overridden.

build

build() -> CompiledKernel

Run steps 1 to 6 and return the compiled container, not yet booted.

boot async

boot() -> BootedKernel

Build, then boot: bundles in order, then @on_boot hooks.

run

run(main: Callable[..., Awaitable[int] | int]) -> int

Boot, call main with its Injected[...] filled, shut down, return its exit code.

Raises:

  • TypeError –

    If main returns anything but an int.

KernelInterface

Bases: Protocol

The kernel, as a service: its identity, environment and what it decided.

name property

name: str

The application's name.

package property

package: str

The application package, dotted; empty in a container built without a kernel.

environment property

environment: str

The environment this container was built for.

debug property

debug: bool

Whether the kernel runs in debug mode.

project_dir property

project_dir: Path

The directory of the nearest pyproject.toml above the application.

bundles property

bundles: tuple[str, ...]

Active bundle names, in dependency order, "kernel" first.

report property

report: KernelReport

What the build decided; available once compiled, before boot.

ContainerBagInterface

Bases: Protocol

The container's parameters, read-only, as an injectable service.

all

all() -> dict[str, object]

Return every parameter, nested.

get

get(name: str) -> object

Return the parameter name.

Raises:

  • ParameterNotFoundError –

    If no such parameter exists.

  • EnvPlaceholderError –

    If it holds an environment placeholder, which is resolved when injected, not read raw.

has

has(name: str) -> bool

Return whether the parameter name exists.

resolve_value

resolve_value(value: object) -> object

Return value with every %name% reference in its strings resolved.

escape_value

escape_value(value: object) -> object

Return value with every % in its strings escaped as %%.

unescape_value

unescape_value(value: object) -> object

Return value with every %% in its strings turned back into %.

ParameterBagInterface

Bases: Protocol

The container's parameters, by dotted name (kernel.project_dir).

Parameters nest: setting app.mailer.host makes app a mapping, and get("app") returns it whole.

clear

clear() -> None

Remove every parameter.

add

add(parameters: Mapping[str, object]) -> None

Merge parameters in, nested mappings merged and leaves replaced.

all

all() -> dict[str, object]

Return every parameter, nested.

get

get(name: str) -> object

Return the parameter name.

Raises:

  • ParameterNotFoundError –

    If no such parameter exists.

remove

remove(name: str) -> None

Remove the parameter name, if set.

set

set(name: str, value: object) -> None

Set the parameter name to value.

has

has(name: str) -> bool

Return whether the parameter name is set.

resolve

resolve() -> None

Replace every %name% reference in every parameter by its value.

resolve_value

resolve_value(value: object) -> object

Return value with every %name% reference in its strings resolved.

escape_value

escape_value(value: object) -> object

Return value with every % in its strings escaped as %%.

unescape_value

unescape_value(value: object) -> object

Return value with every %% in its strings turned back into %.

EnvVarLoaderInterface

Bases: Protocol

Loads variables from somewhere else — a secrets directory, a vault, a remote store.

A service implementing this interface is autoconfigured with the container.env_var_loader tag. Loaders are asked, in registration order, only for a variable the process environment does not set, and each one is loaded once until the processor is reset.

load_env_vars

load_env_vars() -> Mapping[str, str]

Return every variable this loader provides, by name.

EnvVarProcessor

EnvVarProcessor(environ: Mapping[str, str] | None = None, loaders: Iterable[EnvVarLoaderInterface] = (), get_parameter: Callable[[str], object] | None = None)

Bases: EnvVarProcessorInterface

The processor behind every built-in prefix, reading the process environment and loaders.

Resettable: :meth:reset forgets what the loaders provided, so the next lookup asks them again — a worker picks up a rotated secret between messages.

Read environ (the live process environment by default), then loaders.

Parameters:

  • environ (Mapping[str, str] | None, default: None ) –

    Where variables are read first; None reads os.environ at every lookup.

  • loaders (Iterable[EnvVarLoaderInterface], default: () ) –

    Asked, in order, for a variable environ lacks.

  • get_parameter (Callable[[str], object] | None, default: None ) –

    Resolves a parameter for default: and resolve:; without one, those prefixes cannot name one.

reset

reset() -> None

Forget what the loaders provided.

EnvVarProcessorInterface

Bases: Protocol

Processes the prefixes it provides, e.g. int in env("int:PORT").

A service implementing this interface is autoconfigured with the container.env_var_processor tag and consulted for every prefix its :meth:get_provided_types names; the kernel's own EnvVarProcessor provides the built-in ones.

get_env

get_env(prefix: str, name: str, get_env: Callable[[str], object]) -> object

Return the value of prefix:name.

Parameters:

  • prefix (str) –

    The prefix being processed.

  • name (str) –

    What follows it: a variable name, or a further expression ("file:SECRETS" in "json:file:SECRETS") to resolve with get_env.

  • get_env (Callable[[str], object]) –

    Resolves the rest of the chain.

get_provided_types classmethod

get_provided_types() -> Mapping[str, str]

Return each prefix provided, mapped to the types it produces ("int", "array").

Reference dataclass

Reference(service: type[object], qualifier: Hashable | None = None)

Points a config field at a service registered in the container.

Use it where a config would otherwise name something the bundle builds itself — a DSN, say — to have the bundle use a service the application already provides instead: a client with its own connection pool, credentials and lifecycle, which the application keeps closing.

LockConfig(resources={"default": Reference(Redis, "locks")})

A bundle checks it at boot with :meth:exists_in, so a reference to nothing fails the application at startup, and fetches it with :meth:resolve when the service needing it is built.

Attributes:

  • service (type[object]) –

    The type the service is registered under.

  • qualifier (Hashable | None) –

    The qualifier it is registered with, if any.

exists_in

exists_in(container: ContainerInterface) -> bool

Tell whether container provides the service.

resolve async

resolve(container: ContainerInterface) -> object

Return the service from container.

ScopeFactoryInterface

Bases: Protocol

Opens a unit of work on the container it was built for.

The one method mirrors :func:~xtr_dependency_injection.unit_of_work: it opens a scope — or joins the one the container has open — and yields the scoped container, which resolves scoped services as well as singletons.

unit_of_work

unit_of_work(*, join: bool = True) -> AbstractAsyncContextManager[ContainerInterface]

Open a unit of work — or join the one already open — and yield its container.

Parameters:

  • join (bool, default: True ) –

    Join the unit the container has open, if any. False opens one of its own inside it, for work that is new rather than part of what is under way.

Raises:

  • InvalidArgumentTypeError –

    On entering, if the factory was built for a container no kernel built.

ServiceLocator

ServiceLocator(container: ContainerInterface, entries: Mapping[Hashable, ServiceKey])

Bases: ServiceCollectionInterface[T]

Builds services by name, from a container, only when asked.

Build one inside a factory that takes container: ContainerInterface::

def middleware_locator(container: ContainerInterface) -> ServiceLocator[Middleware]:
    return ServiceLocator(container, {name: (Middleware, name) for name in NAMES})

Map each name in entries to the service key it stands for.

get async

get(name: Hashable) -> T

Return the service named name, building it if needed.

Raises:

ServicesResetter

ServicesResetter()

Tracks built resettable singletons and resets them on demand.

Track nothing yet: services are tracked as the container builds them.

track

track(instance: object, method: str) -> None

Remember instance, to call its method on every :meth:reset.

Held weakly when it can be, so being resettable keeps nothing alive: when a weakly held instance is collected the entry is dropped immediately, so a long-running worker never accumulates dead references.

An instance that cannot be weak-referenced — one whose __slots__ omit __weakref__ — is instead held strongly, by a closure over it, so it lives as long as the resetter does. Both cases key the entry by id(instance) to skip a repeat of the same instance; that deduplication is exact because a strongly held instance's id cannot be reused while it is tracked, and a weakly held one's entry is gone (dropped by the collection callback) before its id could be.

reset async

reset() -> None

Call each tracked service's reset method, in tracking order; sync or async.

Every service is reset, whichever of them fail: one left holding the last unit of work's caches would bleed them into the next. Units of work still running are not waited for: each reset must be safe while they run.

Raises:

  • ExceptionGroup –

    Of what every failing reset raised, once all ran.

bundle_active

bundle_active(builder: ContainerBuilder, name: str) -> bool

Return whether the bundle name is active in the build builder sees.

Reads the kernel.bundles parameter the kernel registers before any bundle hook runs. Usable from build onward, where that parameter exists; before then it is absent and this returns False.

named_factory

named_factory(factory: F, name: str) -> F

Name factory name and return it.

A bundle registering one factory per configured name — a store per lock resource, a pool per cache pool — builds each as a closure of the same function, so every one would be reported under that function's name. The container's report, and every error naming the factory, reads far better with lock_store_reports than with store. Only the names change: the function, and how the engine calls it, stay as they are.

The function itself is renamed, not a copy of it: give it a function made for this name — a closure built per qualifier — never one shared by others.

sort_with_priorities

sort_with_priorities(priorities: Mapping[str, int | None], constraints: Mapping[str, Mapping[str, Sequence[str]]], aliases: Mapping[str, Sequence[str]] | None = None) -> dict[str, int]

Sort items by priority first, then apply the constraints.

An explicit priority is a claim: constraints reorder such an item only among the items sharing its priority, and a constraint that would need it to cross a priority is an error. An item without priority is free: its constraints place it, and it adopts the priority its place requires, 0 when that fits.

Parameters:

Returns:

  • dict[str, int] –

    The items in their final order, mapped to their effective priority.

Raises:

  • ServiceOrderError –

    When the constraints are cyclic or contradict an explicit priority.

autoconfigure_tag

autoconfigure_tag(name: str | None = None, /, **attributes: object) -> Callable[[T], T]

Record a single tag rule on this class.

Repeatable: several @autoconfigure_tag(...) on one class accumulate.

is_container_supplied

is_container_supplied(annotation: object) -> bool

Return whether the container fills a parameter annotated annotation.

True for Injected[T], Annotated[T, Autowire(...)] and Annotated[T, Target(...)] — also as a member of a union, such as Injected[T] | None. Also true for a bare ServiceLocator[T], which the container fills with a lazy name-keyed map of the services of T without a marker, the way it fills a bare Sequence[T] or Mapping[Hashable, T]. A library that calls a user's callable — a command, a message handler — asks this to tell the parameters it passes itself from the ones the container fills, so every such library agrees on what a marker is.

A type alias reads as what it stands for: type Mailer = Injected[Smtp] is container-supplied, as Injected[Smtp] is.

on_boot

on_boot(fn: F) -> F
on_boot(*, priority: int = 0) -> Callable[[F], F]
on_boot(fn: F | None = None, /, *, priority: int = 0) -> F | Callable[[F], F]

Run the decorated function once the bundles have booted; highest priority first.

on_shutdown

on_shutdown(fn: F) -> F
on_shutdown(*, priority: int = 0) -> Callable[[F], F]
on_shutdown(fn: F | None = None, /, *, priority: int = 0) -> F | Callable[[F], F]

Run the decorated function first as the kernel shuts down; highest priority first.

when_not

when_not(env: str, /, *envs: str) -> Callable[[T], T]

Leave the decorated object out of the given environments.

Repeating it widens the set. Combined with @when, both must pass.

qualified_name

qualified_name(obj: object) -> str

Return module:qualname for obj when both are strings, else repr.

This is how reports and errors name a provider — a function, class or the like — as opposed to :func:~xtr_dependency_injection.exception._naming.type_name, which names a type in a service key.

current_unit_of_work

current_unit_of_work() -> ContainerInterface | None

Return the unit of work open in this context, or None outside one.

Raises:

  • UnitReadDuringSingletonBuildError –

    If a singleton is being built here, in a kernel built in debug mode: it would keep whichever unit happened to build it.

open_unit_of

open_unit_of(container: ContainerInterface) -> ContainerInterface | None

Return the unit of work open in this context on container's services, if any.

For a service that must work in the unit of whatever is being handled when there is one, and from container itself otherwise. A unit of another container — a second kernel's — is not container's.

Raises: