@inject description

This commit is contained in:
Roman Mogilatov 2015-03-31 14:44:15 +03:00
parent e1009373bc
commit 0db7a67ef2
2 changed files with 44 additions and 64 deletions

View File

@ -127,81 +127,36 @@ assert object_a_1.database is object_a_2.database
assert object_a_1.get_one() == object_a_2.get_one() == 1
```
### Catalogs
Catalogs are named set of providers.
## Example
Also injections could be used by any callable with `@inject` decorator:
```python
"""Concept example of `Objects`."""
"""`@inject` decorator example."""
from objects.catalog import AbstractCatalog
from objects.providers import Singleton
from objects.providers import NewInstance
from objects.injections import KwArg
from objects.injections import Attribute
from objects.injections import inject
import sqlite3
object_a = NewInstance(object)
object_b = NewInstance(object)
class ObjectA(object):
@inject(KwArg('a', object_a))
@inject(KwArg('b', object_b))
def example_callback(a, b):
"""This function has dependencies on object a and b.
"""Example class ObjectA, that has dependency on database."""
def __init__(self, db):
"""Initializer."""
self.db = db
Dependencies are injected using `@inject` decorator.
"""
assert a is not b
assert isinstance(a, object)
assert isinstance(b, object)
class ObjectB(object):
"""Example class ObjectB, that has dependencies on ObjectA and database."""
def __init__(self, a, db):
"""Initializer."""
self.a = a
self.db = db
class Catalog(AbstractCatalog):
"""Catalog of objects providers."""
database = Singleton(sqlite3.Connection,
KwArg('database', ':memory:'),
Attribute('row_factory', sqlite3.Row))
""":type: (objects.Provider) -> sqlite3.Connection"""
object_a = NewInstance(ObjectA,
KwArg('db', database))
""":type: (objects.Provider) -> ObjectA"""
object_b = NewInstance(ObjectB,
KwArg('a', object_a),
KwArg('db', database))
""":type: (objects.Provider) -> ObjectB"""
# Catalog static provides.
a1, a2 = Catalog.object_a(), Catalog.object_a()
b1, b2 = Catalog.object_b(), Catalog.object_b()
assert a1 is not a2
assert b1 is not b2
assert a1.db is a2.db is b1.db is b2.db is Catalog.database()
# Example of inline injections.
@inject(KwArg('a', Catalog.object_a))
@inject(KwArg('b', Catalog.object_b))
@inject(KwArg('database', Catalog.database))
def example(a, b, database):
assert a.db is b.db is database is Catalog.database()
example()
example_callback()
```
### Catalogs
Catalogs are named set of providers.

View File

@ -0,0 +1,25 @@
"""`@inject` decorator example."""
from objects.providers import NewInstance
from objects.injections import KwArg
from objects.injections import inject
object_a = NewInstance(object)
object_b = NewInstance(object)
@inject(KwArg('a', object_a))
@inject(KwArg('b', object_b))
def example_callback(a, b):
"""This function has dependencies on object a and b.
Dependencies are injected using `@inject` decorator.
"""
assert a is not b
assert isinstance(a, object)
assert isinstance(b, object)
example_callback()