FastInject provides lazy dependency injection for Python that makes your code decoupled, testable, uncomplicated and more readable.
Decorate your services with the @injectable
decorator and decorate your function with @inject
. Done!
Your function will now be injected with instances of the required service.
pip install fastinject
- Main Features
- Usage Example
- How to
- Installation
- Dependencies
- License
- Documentation
- Development
- Contributing to FastInject
- 🦥 Lazily declare and register your dependencies
- 🐇 Eagerly validate your dependencies
- 🤸 Flexible
- 🎩 Tailor-made for your app
- 👨🎨 Easy to use with decorators
Below details a minimal use case
We have a service that we want to inject, so we mark it injectable
with a decorator:
import time, datetime
from fastinject import injectable
@injectable() # <-- Just add this decorator to declare the TimeStamp service to be injectable
class TimeStamp:
ts: float
def __init__(self) -> None:
self.ts = time.time()
@property
def datetime_str(self) -> str:
return datetime.datetime.fromtimestamp(self.ts).strftime("%Y-%m-%d %H:%M:%S")
Step 2: Use the service in a function that is injected in
from fastinject import inject
@inject() # <-- This decorator will inject required services in this function
def function_with_injection(ts: TimeStamp):
print(f"In the injected function, the current time is {ts.datetime_str}.")
if __name__ == "__main__":
function_with_injection()
Step 3: Optinonally validate that all injected services can be injected:
from fastinject import get_default_registry
if __name__ == "__main__":
registry = get_default_registry()
# Validate
registry.validate()
function_with_injection()
Injecting services
Inject services that depend on one another
- ServiceConfig: Register multiple dependencies for injection.
- ServiceConfig: Register nested dependencies for injection.
Use the service registy imperatively to get and set dependencies on the fly
- Declare service to be injectable imperatively.
- Declare service to be injectable and declare function to inject imperatively.
Use multiple registries?
Register similar services?
Validation
pip install fastinject
The source code is currently hosted on GitHub at: https://github.com/mike-huls/fastinject
Binary installers for the latest released version are available at the Python Package Index (PyPI).
FastInject is built on injector
, aiming to provide additional features and ease-of-use.
Find the changelog and list of upcoming features here.
Contributions are always welcome; feel free to submit bug reports, bug fixes, feature requests, documentation improvements or enhancements!