Broccoli is a simple dependency injection package based on type annotations
pip install broccoli - Simple - less than 100 lines of code without external dependencies
- Error check - Function signature check on start up - less errors during refactoring
- Fast - Designed to have zero runtime overhead, all dependencies injected either on module load or application start up.
- Powerful - Auto-discovery of dependencies by package and by module
- Convenient - Hackable and elegant programmatic API. Really easy to start using it.
Oups, sorry
Inject dependency to function with type annotations
frombroccoliimportbindclassDependency: passdeffoo(a, bar:Dependency): print(a, bar) bind(foo, Dependency()) foo(1) # prints 1 <__main__.Dependency object at 0x11111b7b8>Inject dependency to module/package
# module foo.pydeffoo(a, b:DependencyA): print(a, b) defbar(a, b:DependencyB): print(a, b) # main.pyfrombroccoliimportinjectfrompackageimportfooinject(foo, DependencyA(), DependencyB()) # orinject('package.foo', DependencyA(), DependencyB())Example with decorator wich inject deps on demand
frombrocolli.fixtures.typesimport*frombroccoliimportDependencydefdependecies(): returnDb(), Service(), Cache() default_dependencies=Dependency(dependecies) @default_dependenciesdefa(db: Db): returndb.query('User').all()Inject deps on application entry point
... default_dependencies=Dependency() @default_dependenciesdefa(db: Db): returndb.query('User').all() if__name__=='__main__': default_dependencies<<dependecies# or evendefault_dependencies<<dependecies()No reason, you can keep using module level variables and singleton objects. But if you know a good example of unit tests for such code don't hesitate to share it.
For feature requests and bug reportssubmit an issue to the GitHub issue tracker for Broccoli.
