Welcome to Injector’s documentation!¶
GitHub (code repository, issues): https://github.com/alecthomas/injector
PyPI (installable, stable distributions): https://pypi.org/project/injector. You can install Injector using pip:
pip install injector
Injector works with CPython 3.6+ and PyPy 3 implementing Python 3.6+.
While dependency injection is easy to do in Python due to its support for keyword arguments, the ease with which objects can be mocked and its dynamic natura, a framework for assisting in this process can remove a lot of boiler-plate from larger applications. That’s where Injector can help. It automatically and transitively provides dependencies for you. As an added benefit, Injector encourages nicely compartmentalised code through the use of modules.
If you’re not sure what dependency injection is or you’d like to learn more about it see:
- The Clean Code Talks - Don’t Look For Things! (a talk by Miško Hevery)
- Inversion of Control Containers and the Dependency Injection pattern (an article by Martin Fowler)
The core values of Injector are:
Simplicity - while being inspired by Guice, Injector does not slavishly replicate its API. Providing a Pythonic API trumps faithfulness. Additionally some features are ommitted because supporting them would be cumbersome and introduce a little bit too much “magic” (member injection, method injection).
Connected to this, Injector tries to be as nonintrusive as possible. For example while you may declare a class’ constructor to expect some injectable parameters, the class’ constructor remains a standard constructor – you may instaniate the class just the same manually, if you want.
No global state – you can have as many
Injectorinstances as you like, each with a different configuration and each with different objects in different scopes. Code like this won’t work for this very reason:
class MyClass: @inject def __init__(t: SomeType): # ... MyClass()
Cooperation with static type checking infrastructure – the API provides as much static type safety as possible and only breaks it where there’s no other option. For example the
Injector.getmethod is typed such that injector.get(SomeType) is statically declared to return an instance of SomeType, therefore making it possible for tools such as mypy to type-check correctly the code using it.