linkd.compose¶
- class Compose[source]¶
Class allowing for “composing” of multiple dependencies into a single object, to help declutter the signatures of functions that require a large number of dependencies.
If you have ever used msgspec, pydantic, or dataclasses this will feel familiar. To use this feature, simply create a subclass of this class and define fields for the dependencies you wish to use.
class ComposedDependencies(linkd.Compose): foo: FooDep bar: BarDep baz: BazDep
Then, in place of specifying
foo,barandbazwithin the function signature, you can request a single object of typeComposedDependencies.async def function(deps: ComposedDependencies): ...
Linkd will automatically try to create an instance of your composed class with all the dependencies that it requires. As with defining dependencies within the function signature, you can use fallback and
IforTrysyntax within the composed class field annotations.Methods, classmethods, staticmethods and properties defined on the subclass are preserved and accessible on instances as normal.
Warning
None of the fields may contain a dependency on a composed class.
- class Expose[source]¶
Class allowing for “exposing” of multiple dependencies to a registry or container from a single factory method. Could help reduce the length of factory chains, for example when creating database connections, you can have a single factory create both the connection pool, and any repository classes you use to abstract any interactions.
As with
linkd.compose.Compose, if you have ever used a dataclasses-like library this will feel familiar. To use this feature, simply create a subclass of this class and define fields for the dependencies you wish to supply.class ExposedDependencies(linkd.Expose): foo: FooDep bar: BarDep baz: BazDep
Then, in place of registering factories for all the dependencies separately, you can instead register a factory for your
Exposesubclass.async def factory() -> ExposedDependencies: ... return ExposedDependencies(foo, bar, baz) registry.register_factory(ExposedDependencies, factory)
Linkd will automatically unpack the
Exposesubclass into individual dependencies, and make them all available to the injection container when any are required. UnlikeCompose, you may only expose dependencies of a single concrete type - unions, conditions (If/Try), or nestedExposedependencies are not permitted and will raise aValueErrorat runtime.