Reference
Main API
The top level import of tidi
provides everything needed it's primary intended use.
tidi.inject
- a decorator that will replace certain keyword arguments with dependencies, based on their type & if they haven't been passed intidi.Injected
- a type alias, wrappingtyping.Annotated
, that indicates that a keyword argument should be injectedtidi.register
- a function that registers an object to be available for injection as a dependencytidi.Provider
- a wrapper class around a function or context manager that will be called to provide a dependencytidi.UNSET
- a sentinel object to indicate that a dependency should be loaded from the registrytidi.field_factory
- a helper function for injecting dependencies into dataclass fields
tidi.inject
, tidi.Injected
, & tidi.UNSET
@tidi.inject
will injects dependencies into keyword arguments with the tidi.Injected
type
annotation.
If the default value is tidi.UNSET
, it will search for that dependency in the
registry.
See the tidi.decorator
documentation for more detail.
tidi.register
To register a dependency instance, simple call the tidi.register
function
This puts it into the default registry which is shared across
See the tidi.registry
documentation for more detail.
tidi.Provider
For more control over what instance is injected, give a provider of the dependency as a function, or as a context manager.
The given provider will be called each time the function is called.
@tidi.inject
def get_users(db: tidi.Injected[Database] = tidi.Provider(load_database)):
db.query(Users).all()
See the tidi.decorator
documentation for more detail.
tidi.field_factory
When working with dataclasses, the inject
decorator doesn't work, so use the
field_factory
convenience function to inject the dependency into a field upon
instance creation.
from dataclasses import dataclass, field
@dataclass
class UserQuery:
name: str
db: Database = field(default_factory=tidi.field_factory(Database))
user_query = UserQuery()
execute_user_query(user_query)
Modules
Tidi's codebase consists of the following four, relatively small modules:
tidi.decorator
- provides the main inject decorator, usingtidi.parameters
to determine which parameters of the wrapped function to replacetidi.parameters
- background wrapper of the builtininspect.Parameter
class for determining which function parameters are annotatedtidi.registry
- provides simple registry class for holding dependency instances, stored in a dictionary (map), using their type as the keytidi.resolver
- contains the logic used to either find an object from the registry or from a provider function