Fast and easy dependency injection framework.
Project description
Basic usage
Create an injectable
If you wish to inject a singleton, use singleton
decorator.
from injection import singleton
@singleton
class Singleton:
""" class implementation """
If you wish to inject a new instance each time, use injectable
decorator.
from injection import injectable
@injectable
class Injectable:
""" class implementation """
Inject an instance
To inject one or several instances, use inject
decorator.
Don't forget to annotate type of parameter to inject.
from injection import inject
@inject
def my_function(instance: Injectable):
""" function implementation """
If inject
decorates a class, it will be applied to the __init__
method.
Especially useful for dataclasses:
from dataclasses import dataclass
from injection import inject
@inject
@dataclass
class DataClass:
instance: Injectable = ...
Inheritance
In the case of inheritance, you can use the decorator parameter on
to link the injection to one or several other
classes.
Warning: if the child class is in another file, make sure that file is imported before injection.
See load_package
function.
Example with one class:
from injection import singleton
class A:
...
@singleton(on=A)
class B(A):
...
Example with several classes:
from injection import singleton
class A:
...
class B(A):
...
@singleton(on=(A, B))
class C(B):
...
Recipes
A recipe is a function that tells the injector how to construct the instance to be injected. It is important to specify the return type annotation when defining the recipe.
from injection import singleton
@singleton
def my_recipe() -> Singleton:
""" recipe implementation """
Auto inject
By default, injectable
and singleton
decorators will automatically apply @inject
to the decorated class or
function. To disable it, set the auto_inject
parameter to False
.
from injection import singleton
@singleton(auto_inject=False)
class Singleton:
""" class implementation """
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for python_injection-0.5.10-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | ee438a529f7a58fd6d7d734efdae362ab7f0b6ee4ce402d21f28155617926c44 |
|
MD5 | 4e797f2214cb8e10f604d3537a727d66 |
|
BLAKE2b-256 | e4daa3c052b51d42f7325295828d53f1e6561c15a7793f9e8d3d677271efbac0 |