Add simple example.

This commit is contained in:
Alec Thomas 2013-06-27 10:19:19 -04:00
parent 91f72d7781
commit 76cb00592e
2 changed files with 131 additions and 201 deletions

View File

@ -1,69 +1,77 @@
Injector - Python dependency injection framework, inspired by Guice Injector - Python dependency injection framework, inspired by Guice
###################################################################### ===================================================================
.. image:: https://secure.travis-ci.org/alecthomas/injector.png?branch=master [![image](https://secure.travis-ci.org/alecthomas/injector.png?branch=master)](https://travis-ci.org/alecthomas/injector)
:target: https://travis-ci.org/alecthomas/injector
Introduction Introduction
============ ------------
Dependency injection as a formal pattern is less useful in Python than in other Dependency injection as a formal pattern is less useful in Python than in other languages, primarily due to its support for keyword arguments, the ease with which objects can be mocked, and its dynamic nature.
languages, primarily due to its support for keyword arguments, the ease with
which objects can be mocked, and its dynamic nature.
That said, a framework for assisting in this process can remove a lot of That said, 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 keyword arguments with their values. As an added benefit, Injector encourages nicely compartmentalised code through the use of `Module` s.
boiler-plate from larger applications. That's where Injector can help. It
automatically and transitively provides keyword arguments with their values. As
an added benefit, Injector encourages nicely compartmentalised code through the
use of ``Module`` s.
While being inspired by Guice, it does not slavishly replicate its API. While being inspired by Guice, it does not slavishly replicate its API. Providing a Pythonic API trumps faithfulness.
Providing a Pythonic API trumps faithfulness.
Supported Python versions Supported Python versions
========================= -------------------------
Injector work with the following Python interpreters: Injector work with the following Python interpreters:
* CPython 2.6, 2.7, 3.2, 3.3 - CPython 2.6, 2.7, 3.2, 3.3
* PyPy 1.9 - PyPy 1.9
A Quick Example
---------------
>>> from injector import Injector, inject
>>> class Inner(object):
... def __init__(self):
... self.forty_two = 42
...
>>> class Outer(object):
... @inject(inner=Inner)
... def __init__(self, inner):
... self.inner = inner
...
>>> injector = Injector()
>>> outer = injector.get(Outer)
>>> outer.inner.forty_two
42
A Full Example A Full Example
============== --------------
Here's a full example to give you a taste of how Injector works::
Here's a full example to give you a taste of how Injector works:
>>> from injector import Module, Key, provides, Injector, inject, singleton >>> from injector import Module, Key, provides, Injector, inject, singleton
We'll use an in-memory SQLite database for our example:: We'll use an in-memory SQLite database for our example:
>>> import sqlite3 >>> import sqlite3
And make up an imaginary RequestHandler class that uses the SQLite connection:: And make up an imaginary RequestHandler class that uses the SQLite connection:
>>> class RequestHandler(object): >>> class RequestHandler(object):
... @inject(db=sqlite3.Connection) ... @inject(db=sqlite3.Connection)
... def __init__(self, db): ... def __init__(self, db):
... self._db = db ... self._db = db
...
... def get(self): ... def get(self):
... cursor = self._db.cursor() ... cursor = self._db.cursor()
... cursor.execute('SELECT key, value FROM data ORDER by key') ... cursor.execute('SELECT key, value FROM data ORDER by key')
... return cursor.fetchall() ... return cursor.fetchall()
Next, for the sake of the example, we'll create a "configuration" annotated Next, for the sake of the example, we'll create a "configuration" annotated type:
type::
>>> Configuration = Key('configuration') >>> Configuration = Key('configuration')
`Key` is used to uniquely identifies the configuration dictionary. Next, we Key is used to uniquely identifies the configuration dictionary. Next, we bind the configuration to the injector, using a module:
bind the configuration to the injector, using a module::
>>> def configure_for_testing(binder): >>> def configure_for_testing(binder):
... configuration = {'db_connection_string': ':memory:'} ... configuration = {'db_connection_string': ':memory:'}
... binder.bind(Configuration, to=configuration, scope=singleton) ... binder.bind(Configuration, to=configuration, scope=singleton)
Next we create a module that initialises the DB. It depends on the 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 a Connection object:
configuration provided by the above module to create a new DB connection, then
populates it with some dummy data, and provides a Connection object::
>>> class DatabaseModule(Module): >>> class DatabaseModule(Module):
... @singleton ... @singleton
@ -76,110 +84,79 @@ populates it with some dummy data, and provides a Connection object::
... cursor.execute('INSERT OR REPLACE INTO data VALUES ("hello", "world")') ... cursor.execute('INSERT OR REPLACE INTO data VALUES ("hello", "world")')
... return conn ... return conn
(Note how we have decoupled configuration from our database initialisation (Note how we have decoupled configuration from our database initialisation code.)
code.)
Finally, we initialise an Injector and use it to instantiate a RequestHandler Finally, we initialise an Injector and use it to instantiate a RequestHandler instance. This first transitively constructs a sqlite3.Connection object, and the Configuration dictionary that it in turn requires, then instantiates our \`RequestHandler\`:
instance. This first transitively constructs a `sqlite3.Connection` object,
and the `Configuration` dictionary that it in turn requires, then instantiates
our `RequestHandler`::
>>> injector = Injector([configure_for_testing, DatabaseModule()]) >>> injector = Injector([configure_for_testing, DatabaseModule()])
>>> handler = injector.get(RequestHandler) >>> handler = injector.get(RequestHandler)
>>> tuple(map(str, handler.get()[0])) # py3/py2 compatibility hack >>> tuple(map(str, handler.get()[0])) # py3/py2 compatibility hack
('hello', 'world') ('hello', 'world')
We can also veryify that our Configuration and SQLite connections are indeed We can also veryify that our Configuration and SQLite connections are indeed singletons within the Injector:
singletons within the Injector::
>>> injector.get(Configuration) is injector.get(Configuration) >>> injector.get(Configuration) is injector.get(Configuration)
True True
>>> injector.get(sqlite3.Connection) is injector.get(sqlite3.Connection) >>> injector.get(sqlite3.Connection) is injector.get(sqlite3.Connection)
True True
You're probably thinking something like: "this is a large amount of work just You'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:
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:
1. Forces decoupling. In our example, this is illustrated by decoupling > 1. Forces decoupling. In our example, this is illustrated by decoupling our configuration and database configuration.
our configuration and database configuration. > 2. After a type is configured, it can be injected anywhere with no additional effort. Simply @inject and it appears. We don't really illustrate that here, but you can imagine adding an arbitrary number of RequestHandler subclasses, all of which will automatically have a DB connection provided.
2. After a type is configured, it can be injected anywhere with no
additional effort. Simply @inject and it appears. We don't really
illustrate that here, but you can imagine adding an arbitrary number of
RequestHandler subclasses, all of which will automatically have a DB
connection provided.
Terminology Terminology
=========== -----------
At its heart, Injector is simply a dictionary for mapping types to things that
create instances of those types. This could be as simple as:: At its heart, Injector is simply a dictionary for mapping types to things that create instances of those types. This could be as simple as:
{str: 'an instance of a string'} {str: 'an instance of a string'}
For those new to dependency-injection and/or Guice, though, some of the For those new to dependency-injection and/or Guice, though, some of the terminology used may not be obvious.
terminology used may not be obvious.
Provider ### Provider
--------
A means of providing an instance of a type. Built-in providers include
``ClassProvider`` (creates a new instance from a class),
``InstanceProvider`` (returns an existing instance directly),
``CallableProvider`` (provides an instance by calling a function).
Scope A means of providing an instance of a type. Built-in providers include `ClassProvider` (creates a new instance from a class), `InstanceProvider` (returns an existing instance directly), `CallableProvider` (provides an instance by calling a function).
-----
By default, providers are executed each time an instance is required. Scopes
allow this behaviour to be customised. For example, ``SingletonScope``
(typically used through the class decorator ``singleton``), can be used to
always provide the same instance of a class.
Other examples of where scopes might be a threading scope, where instances are ### Scope
provided per-thread, or a request scope, where instances are provided
per-HTTP-request.
The default scope is ``NoScope``. By default, providers are executed each time an instance is required. Scopes allow this behaviour to be customised. For example, `SingletonScope` (typically used through the class decorator `singleton`), can be used to always provide the same instance of a class.
Binding Key Other examples of where scopes might be a threading scope, where instances are provided per-thread, or a request scope, where instances are provided per-HTTP-request.
-----------
A binding key uniquely identifies a provider of a type. It is effectively a
tuple of ``(type, annotation)`` where ``type`` is the type to be provided and
``annotation`` is additional, optional, uniquely identifying information for
the type.
For example, the following are all unique binding keys for ``str``:: The default scope is `NoScope`.
### Binding Key
A binding key uniquely identifies a provider of a type. It is effectively a tuple of `(type, annotation)` where `type` is the type to be provided and `annotation` is additional, optional, uniquely identifying information for the type.
For example, the following are all unique binding keys for `str`:
(str, 'name') (str, 'name')
(str, 'description') (str, 'description')
For a generic type such as ``str``, annotations are very useful for unique For a generic type such as `str`, annotations are very useful for unique identification.
identification.
As an *alternative* convenience to using annotations, ``Key`` may be used As an *alternative* convenience to using annotations, `Key` may be used to create unique types as necessary:
to create unique types as necessary::
>>> from injector import Key >>> from injector import Key
>>> Name = Key('name') >>> Name = Key('name')
>>> Description = Key('description') >>> Description = Key('description')
Which may then be used as binding keys, without annotations, as they already Which may then be used as binding keys, without annotations, as they already uniquely identify a particular provider:
uniquely identify a particular provider::
(Name, None) (Name, None)
(Description, None) (Description, None)
Though of course, annotations may still be used with these types, like any Though of course, annotations may still be used with these types, like any other type.
other type.
Annotation ### Annotation
----------
An annotation is additional unique information about a type to avoid binding
key collisions. It creates a new unique binding key for an existing type.
Binding An annotation is additional unique information about a type to avoid binding key collisions. It creates a new unique binding key for an existing type.
-------
A binding is the mapping of a unique binding key to a corresponding provider. ### Binding
For example::
A binding is the mapping of a unique binding key to a corresponding provider. For example:
>>> from injector import InstanceProvider >>> from injector import InstanceProvider
>>> bindings = { >>> bindings = {
@ -187,17 +164,13 @@ For example::
... (Description, None): InstanceProvider('A man of astounding insight'), ... (Description, None): InstanceProvider('A man of astounding insight'),
... } ... }
Binder ### Binder
------
The ``Binder`` is simply a convenient wrapper around the dictionary
that maps types to providers. It provides methods that make declaring bindings
easier.
Module The `Binder` is simply a convenient wrapper around the dictionary that maps types to providers. It provides methods that make declaring bindings easier.
------
A ``Module`` configures bindings. It provides methods that simplify the ### Module
process of binding a key to a provider. For example the above bindings would be
created with:: A `Module` configures bindings. It provides methods that simplify the process of binding a key to a provider. For example the above bindings would be created with:
>>> from injector import Module >>> from injector import Module
>>> class MyModule(Module): >>> class MyModule(Module):
@ -205,8 +178,7 @@ created with::
... binder.bind(Name, to='Sherlock') ... binder.bind(Name, to='Sherlock')
... binder.bind(Description, to='A man of astounding insight') ... binder.bind(Description, to='A man of astounding insight')
For more complex instance construction, methods decorated with For more complex instance construction, methods decorated with `@provides` will be called to resolve binding keys:
``@provides`` will be called to resolve binding keys::
>>> from injector import provides >>> from injector import provides
>>> class MyModule(Module): >>> class MyModule(Module):
@ -217,15 +189,11 @@ For more complex instance construction, methods decorated with
... def describe(self): ... def describe(self):
... return 'A man of astounding insight (at %s)' % time.time() ... return 'A man of astounding insight (at %s)' % time.time()
Injection ### Injection
---------
Injection is the process of providing an instance of a type, to a method that
uses that instance. It is achieved with the ``inject`` decorator. Keyword
arguments to inject define which arguments in its decorated method should be
injected, and with what.
Here is an example of injection on a module provider method, and on the Injection is the process of providing an instance of a type, to a method that uses that instance. It is achieved with the `inject` decorator. Keyword arguments to inject define which arguments in its decorated method should be injected, and with what.
constructor of a normal class::
Here is an example of injection on a module provider method, and on the constructor of a normal class:
>>> from injector import inject >>> from injector import inject
>>> class User(object): >>> class User(object):
@ -247,25 +215,20 @@ constructor of a normal class::
... def describe(self, name): ... def describe(self, name):
... return '%s is a man of astounding insight' % name ... return '%s is a man of astounding insight' % name
You can also ``inject``-decorate class itself. This code:: You can also `inject`-decorate class itself. This code:
>>> @inject(name=Name) >>> @inject(name=Name)
... class Item(object): ... class Item(object):
... pass ... pass
is equivalent to:: is equivalent to:
>>> class Item(object): >>> class Item(object):
... @inject(name=Name) ... @inject(name=Name)
... def __init__(self, name): ... def __init__(self, name):
... self.name = name ... self.name = name
**Note**: You can also begin the name of injected member with an underscore(s) **Note**: You can also begin the name of injected member with an underscore(s) (to indicate the member being private for example). In such case the member will be injected using the name you specified, but corresponding parameter in a constructor (let's say you instantiate the class manually) will have the underscore prefix stripped (it makes it consistent with most of the usual parameter names):
(to indicate the member being private for example). In such case the member
will be injected using the name you specified, but corresponding parameter in
a constructor (let's say you instantiate the class manually) will have the
underscore prefix stripped (it makes it consistent with most of the usual
parameter names)::
>>> @inject(_y=int) >>> @inject(_y=int)
... class X(object): ... class X(object):
@ -285,29 +248,25 @@ parameter names)::
>>> x2._y >>> x2._y
2 2
### Injector
Injector The `Injector` brings everything together. It takes a list of `Module` s, and configures them with a binder, effectively creating a dependency graph:
--------
The ``Injector`` brings everything together. It takes a list of
``Module`` s, and configures them with a binder, effectively creating a
dependency graph::
>>> from injector import Injector >>> from injector import Injector
>>> injector = Injector([UserModule(), UserAttributeModule()]) >>> injector = Injector([UserModule(), UserAttributeModule()])
You can also pass classes instead of instances to ``Injector``, it will You can also pass classes instead of instances to `Injector`, it will instantiate them for you:
instantiate them for you::
>>> injector = Injector([UserModule, UserAttributeModule]) >>> injector = Injector([UserModule, UserAttributeModule])
The injector can then be used to acquire instances of a type, either directly:: The injector can then be used to acquire instances of a type, either directly:
>>> injector.get(Name) >>> injector.get(Name)
'Sherlock' 'Sherlock'
>>> injector.get(Description) >>> injector.get(Description)
'Sherlock is a man of astounding insight' 'Sherlock is a man of astounding insight'
Or transitively:: Or transitively:
>>> user = injector.get(User) >>> user = injector.get(User)
>>> isinstance(user, User) >>> isinstance(user, User)
@ -317,10 +276,9 @@ Or transitively::
>>> user.description >>> user.description
'Sherlock is a man of astounding insight' 'Sherlock is a man of astounding insight'
Assisted injection ### Assisted injection
------------------
Sometimes there are classes that have injectable and non-injectable parameters in their Sometimes there are classes that have injectable and non-injectable parameters in their constructors. Let's have for example:
constructors. Let's have for example::
>>> class Database(object): pass >>> class Database(object): pass
@ -333,12 +291,9 @@ constructors. Let's have for example::
... def __init__(self, user): ... def __init__(self, user):
... pass ... pass
You may want to have database connection ``db`` injected into ``UserUpdater`` constructor, You may want to have database connection `db` injected into `UserUpdater` constructor, but in the same time provide `user` object by yourself, and assuming that `user` object is a value object and there's many users in your application it doesn't make much sense to inject objects of class `User`.
but in the same time provide ``user`` object by yourself, and assuming that ``user`` object
is a value object and there's many users in your application it doesn't make much sense
to inject objects of class ``User``.
In this situation there's technique called Assisted injection:: In this situation there's technique called Assisted injection:
>>> from injector import AssistedBuilder >>> from injector import AssistedBuilder
>>> injector = Injector() >>> injector = Injector()
@ -346,13 +301,9 @@ In this situation there's technique called Assisted injection::
>>> user = User('John') >>> user = User('John')
>>> user_updater = builder.build(user=user) >>> user_updater = builder.build(user=user)
This way we don't get ``UserUpdater`` directly but rather a builder object. Such builder This way we don't get `UserUpdater` directly but rather a builder object. Such builder has `build(**kwargs)` method which takes non-injectable parameters, combines them with injectable dependencies of `UserUpdater` and calls `UserUpdater` initializer using all of them.
has ``build(**kwargs)`` method which takes non-injectable parameters, combines
them with injectable dependencies of ``UserUpdater`` and calls ``UserUpdater`` initializer
using all of them.
``AssistedBuilder(X)`` is injectable just as anything else, if you need instance of it you `AssistedBuilder(X)` is injectable just as anything else, if you need instance of it you just ask for it like that:
just ask for it like that::
>>> @inject(updater_builder=AssistedBuilder(UserUpdater)) >>> @inject(updater_builder=AssistedBuilder(UserUpdater))
... class NeedsUserUpdater(object): ... class NeedsUserUpdater(object):
@ -361,14 +312,11 @@ just ask for it like that::
More information on this topic: More information on this topic:
* `"How to use Google Guice to create objects that require parameters?" on Stack Overflow <http://stackoverflow.com/questions/996300/how-to-use-google-guice-to-create-objects-that-require-parameters>`_ - ["How to use Google Guice to create objects that require parameters?" on Stack Overflow](http://stackoverflow.com/questions/996300/how-to-use-google-guice-to-create-objects-that-require-parameters)
* `Google Guice assisted injection <http://code.google.com/p/google-guice/wiki/AssistedInject>`_
Child injectors
---------------
Concept similar to Guice's child injectors is supported by ``Injector``. This way you can \* [Google Guice assisted injection](http://code.google.com/p/google-guice/wiki/AssistedInject) Child injectors ---------------
have one injector that inherits bindings from other injector (parent) but these bindings
can be overriden in it and it doesn't affect parent injector bindings:: Concept similar to Guice's child injectors is supported by `Injector`. This way you can have one injector that inherits bindings from other injector (parent) but these bindings can be overriden in it and it doesn't affect parent injector bindings:
>>> def configure_parent(binder): >>> def configure_parent(binder):
... binder.bind(str, to='asd') ... binder.bind(str, to='asd')
@ -384,11 +332,7 @@ can be overriden in it and it doesn't affect parent injector bindings::
>>> child.get(str), child.get(int) >>> child.get(str), child.get(int)
('qwe', 42) ('qwe', 42)
**Note**: Default scopes are bound only to root injector. Binding them manually to child **Note**: Default scopes are bound only to root injector. Binding them manually to child injectors will result in unexpected behaviour. **Note 2**: Once a binding key is present in parent injector scope (like `singleton` scope), provider saved there takes predecence when binding is overridden in child injector in the same scope. This behaviour is subject to change:
injectors will result in unexpected behaviour.
**Note 2**: Once a binding key is present in parent injector scope (like ``singleton``
scope), provider saved there takes predecence when binding is overridden in child injector in
the same scope. This behaviour is subject to change::
>>> def configure_parent(binder): >>> def configure_parent(binder):
... binder.bind(str, to='asd', scope=singleton) ... binder.bind(str, to='asd', scope=singleton)
@ -403,20 +347,18 @@ the same scope. This behaviour is subject to change::
>>> parent.get(str) # wat >>> parent.get(str) # wat
'qwe' 'qwe'
Scopes Scopes
====== ------
Singletons ### Singletons
----------
Singletons are declared by binding them in the SingletonScope. This can be done
in three ways:
1. Decorating the class with ``@singleton``. Singletons are declared by binding them in the SingletonScope. This can be done in three ways:
2. Decorating a ``@provides(X)`` decorated Module method with ``@singleton``.
3. Explicitly calling ``binder.bind(X, scope=singleton)``.
A (redunant) example showing all three methods:: > 1. Decorating the class with `@singleton`.
> 2. Decorating a `@provides(X)` decorated Module method with `@singleton`.
> 3. Explicitly calling `binder.bind(X, scope=singleton)`.
A (redunant) example showing all three methods:
>>> @singleton >>> @singleton
... class Thing(object): pass ... class Thing(object): pass
@ -428,59 +370,44 @@ A (redunant) example showing all three methods::
... def provide_thing(self): ... def provide_thing(self):
... return Thing() ... return Thing()
### Implementing new Scopes
Implementing new Scopes In the above description of scopes, we glossed over a lot of detail. In particular, how one would go about implementing our own scopes.
-----------------------
In the above description of scopes, we glossed over a lot of detail. In
particular, how one would go about implementing our own scopes.
Basically, there are two steps. First, subclass ``Scope`` and implement Basically, there are two steps. First, subclass `Scope` and implement `Scope.get`:
``Scope.get``::
>>> from injector import Scope >>> from injector import Scope
>>> class CustomScope(Scope): >>> class CustomScope(Scope):
... def get(self, key, provider): ... def get(self, key, provider):
... return provider ... return provider
Then create a global instance of ``ScopeDecorator`` to allow classes to be Then create a global instance of `ScopeDecorator` to allow classes to be easily annotated with your scope:
easily annotated with your scope::
>>> from injector import ScopeDecorator >>> from injector import ScopeDecorator
>>> customscope = ScopeDecorator(CustomScope) >>> customscope = ScopeDecorator(CustomScope)
This can be used like so: This can be used like so:
>>> @customscope > \>\>\> @customscope ... class MyClass(object): ... pass
... class MyClass(object):
... pass
Scopes are bound in modules with the ``Binder.bind_scope`` method:: Scopes are bound in modules with the `Binder.bind_scope` method:
>>> class MyModule(Module): >>> class MyModule(Module):
... def configure(self, binder): ... def configure(self, binder):
... binder.bind_scope(CustomScope) ... binder.bind_scope(CustomScope)
Scopes can be retrieved from the injector, as with any other instance. They are Scopes can be retrieved from the injector, as with any other instance. They are singletons across the life of the injector:
singletons across the life of the injector::
>>> injector = Injector([MyModule()]) >>> injector = Injector([MyModule()])
>>> injector.get(CustomScope) is injector.get(CustomScope) >>> injector.get(CustomScope) is injector.get(CustomScope)
True True
For scopes with a transient lifetime, such as those tied to HTTP requests, the For scopes with a transient lifetime, such as those tied to HTTP requests, the usual solution is to use a thread or greenlet-local cache inside the scope. The scope is "entered" in some low-level code by calling a method on the scope instance that creates this cache. Once the request is complete, the scope is "left" and the cache cleared.
usual solution is to use a thread or greenlet-local cache inside the scope. The
scope is "entered" in some low-level code by calling a method on the scope
instance that creates this cache. Once the request is complete, the scope is
"left" and the cache cleared.
Tests Tests
===== -----
When you use unit test framework such as ``unittest2`` or ``nose`` you can also When you use unit test framework such as `unittest2` or `nose` you can also profit from `injector`. However, manually creating injectors and test classes can be quite annoying. There is, however, `with_injector` method decorator which has parameters just as `Injector` construtor and installes configured injector into class instance on the time of method call:
profit from ``injector``. However, manually creating injectors and test classes
can be quite annoying. There is, however, ``with_injector`` method decorator which
has parameters just as ``Injector`` construtor and installes configured injector into
class instance on the time of method call::
>>> from injector import Module, with_injector >>> from injector import Module, with_injector
>>> class UsernameModule(Module): >>> class UsernameModule(Module):
@ -496,11 +423,9 @@ class instance on the time of method call::
... def test_username(self, username): ... def test_username(self, username):
... assert (username == 'Maria') ... assert (username == 'Maria')
*Each* method call re-initializes ``Injector`` - if you want to you can also put *Each* method call re-initializes `Injector` - if you want to you can also put `with_injector` decorator on class constructor.
``with_injector`` decorator on class constructor.
After such call all ``inject``-decorated methods will work just as you'd expect After such call all `inject`-decorated methods will work just as you'd expect them to work.
them to work.
Logging Logging
======= =======
@ -510,17 +435,22 @@ Injector uses standard :mod:`logging` module, the logger name is ``injector``.
By default ``injector`` logger is configured to use :class:`logging.NullHandler`. By default ``injector`` logger is configured to use :class:`logging.NullHandler`.
Thread safety Thread safety
============= -------------
The following functions are thread safe: The following functions are thread safe:
* ``Injector.get`` - `Injector.get`
* injection provided by ``inject`` decorator (please note, however, that it doesn't say anything about decorated function thread safety) - injection provided by `inject` decorator (please note, however, that it doesn't say anything about decorated function thread safety)
Footnote Footnote
======== --------
This framework is similar to snake-guice, but aims for simplification. This framework is similar to snake-guice, but aims for simplification.
:copyright: (c) 2010 by Alec Thomas copyright
:license: BSD 1. 2010 by Alec Thomas
license
BSD

View File

@ -1,2 +1,2 @@
[pytest] [pytest]
addopts = -rsxX -q --doctest-modules --doctest-glob=README.rst injector.py injector_test.py README.rst addopts = -rsxX -q --doctest-modules --doctest-glob=README.md injector.py injector_test.py README.md