Package: injector
IntroductionWhile 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 nature, 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 omitted 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 instantiate the class just the same manually,
if you want.No global state – you can have as manyInjectorinstances 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:classMyClass:@injectdef__init__(t:SomeType):# ...MyClass()This is simply because there’s no globalInjectorto use. You
need to be explicit and useInjector.get,Injector.create_objector injectMyClassinto the place that needs it.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 theInjector.getmethod is typed such thatinjector.get(SomeType)is statically
declared to return an instance ofSomeType, therefore making it
possible for tools such asmypyto type-check correctly the code using it.The client code only knows about dependency injection to the extent
it needs –`inject<https://injector.readthedocs.io/en/latest/api.html#injector.inject>`__,`Inject<https://injector.readthedocs.io/en/latest/api.html#injector.Inject>`__
and`NoInject<https://injector.readthedocs.io/en/latest/api.html#injector.NoInject>`__
are simple markers that don’t really do anything on their own and
your code can run just fine without Injector orchestrating things.How to get Injector?GitHub (code repository, issues):https://github.com/alecthomas/injectorPyPI (installable, stable distributions):https://pypi.org/project/injector/. You can install it using pip:pipinstallinjectorDocumentation:https://injector.readthedocs.orgChange log:https://injector.readthedocs.io/en/latest/changelog.htmlInjector works with CPython 3.7+ and PyPy 3 implementing Python 3.7+.A Quick Example>>>frominjectorimportInjector,inject>>>classInner:...def__init__(self):...self.forty_two=42...>>>classOuter:...@inject...def__init__(self,inner:Inner):...self.inner=inner...>>>injector=Injector()>>>outer=injector.get(Outer)>>>outer.inner.forty_two42Or withdataclassesif you like:fromdataclassesimportdataclassfrominjectorimportInjector,injectclassInner:def__init__(self):self.forty_two=42@inject@dataclassclassOuter:inner:Innerinjector=Injector()outer=injector.get(Outer)print(outer.inner.forty_two)# Prints 42A Full ExampleHere’s a full example to give you a taste of how Injector works:>>>frominjectorimportModule,provider,Injector,inject,singletonWe’ll use an in-memory SQLite database for our example:>>>importsqlite3And make up an imaginaryRequestHandlerclass that uses the SQLite
connection:>>>classRequestHandler:...@inject...def__init__(self,db:sqlite3.Connection):...self._db=db......defget(self):...cursor=self._db.cursor()...cursor.execute('SELECT key, value FROM data ORDER by key')...returncursor.fetchall()Next, for the sake of the example, we’ll create a configuration type:>>>classConfiguration:...def__init__(self,connection_string):...self.connection_string=connection_stringNext, we bind the configuration to the injector, using a module:>>>defconfigure_for_testing(binder):...configuration=Configuration(':memory:')...binder.bind(Configuration,to=configuration,scope=singleton)Next we create a module that initialises the DB. It depends on the
configuration provided by the above module to create a new DB
connection, then populates it with some dummy data, and provides aConnectionobject:>>>classDatabaseModule(Module):...@singleton...@provider...defprovide_sqlite_connection(self,configuration:Configuration)->sqlite3.Connection:...conn=sqlite3.connect(configuration.connection_string)...cursor=conn.cursor()...cursor.execute('CREATE TABLE IF NOT EXISTS data (key PRIMARY KEY, value)')...cursor.execute('INSERT OR REPLACE INTO data VALUES ("hello", "world")')...returnconn(Note how we have decoupled configuration from our database
initialisation code.)Finally, we initialise anInjectorand use it to instantiate aRequestHandlerinstance. This first transitively constructs asqlite3.Connectionobject, and the Configuration dictionary that it
in turn requires, then instantiates ourRequestHandler:>>>injector=Injector([configure_for_testing,DatabaseModule()])>>>handler=injector.get(RequestHandler)>>>tuple(map(str,handler.get()[0]))# py3/py2 compatibility hack('hello','world')We can also verify that ourConfigurationandSQLiteconnections
are indeed singletons within the Injector:>>>injector.get(Configuration)isinjector.get(Configuration)True>>>injector.get(sqlite3.Connection)isinjector.get(sqlite3.Connection)TrueYou’re probably thinking something like: “this is a large amount of work
just to give me a database connection”, and you are correct; dependency
injection is typically not that useful for smaller projects. It comes
into its own on large projects where the up-front effort pays for itself
in two ways:Forces decoupling. In our example, this is illustrated by decoupling
our configuration and database configuration.After a type is configured, it can be injected anywhere with no
additional effort. Simply@injectand it appears. We don’t really
illustrate that here, but you can imagine adding an arbitrary number
ofRequestHandlersubclasses, all of which will automatically
have a DB connection provided.FootnoteThis framework is similar to snake-guice, but aims for simplification.© Copyright 2010-2013 to Alec Thomas, under the BSD license