IoC framework driven by annotations and type hints
Project description
Touchstone
Touchstone is an annotations-driven Inversion of Control container for Python 3.6 and above.
Learn by Example
Auto Wiring
from touchstone import Container
class Child:
pass
class Parent:
def __init__(self, child: Child) -> None:
self.child = child
container = Container()
parent = container.make(Parent)
assert isinstance(parent.child, Child)
Interface Binding
from touchstone import Container
class AbstractChild:
pass
class Child(AbstractChild):
pass
class Parent:
def __init__(self, child: AbstractChild) -> None:
self.child = child
container = Container()
container.bind(AbstractChild, Child)
parent = container.make(Parent)
assert isinstance(parent.child, Child)
Binding with Factory Methods
from touchstone import Container
class Child:
def __init__(self, name: str) -> None:
self.name = name
class Parent:
def __init__(self, child: Child) -> None:
self.child = child
container = Container()
container.bind(Child, lambda: Child('them'))
parent = container.make(Parent)
assert isinstance(parent.child, Child)
assert parent.child.name == 'them'
Binding Singletons
from touchstone import Container, SINGLETON
class Child:
def __init__(self, name: str) -> None:
self.name = name
class Parent:
def __init__(self, child: Child) -> None:
self.child = child
container = Container()
them_child = Child('them')
container.bind_instance(Child, them_child)
# Or...
container.bind(Child, lambda: them_child, lifetime_strategy=SINGLETON)
parent = container.make(Parent)
assert isinstance(parent.child, Child)
assert parent.child is them_child
Contextual Binding
from touchstone import Container
class Child:
def __init__(self, name: str) -> None:
self.name = name
class Parent:
def __init__(self, child1: Child, child2: Child) -> None:
self.child1 = child1
self.child2 = child2
container = Container()
container.bind_contextual(when=Parent, wants=Child, called='child1', give=lambda: Child('her'))
container.bind_contextual(when=Parent, wants=Child, called='child2', give=lambda: Child('him'))
parent = container.make(Parent)
assert isinstance(parent.child1, Child)
assert isinstance(parent.child2, Child)
assert parent.child1.name == 'her'
assert parent.child2.name == 'him'
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
touchstone-0.2.0.tar.gz
(6.2 kB
view hashes)
Built Distribution
touchstone-0.2.0-py3-none-any.whl
(19.5 kB
view hashes)
Close
Hashes for touchstone-0.2.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d9bf867c94f4bec030cdd16ce89ee31142b1443c6a9326ed764437069cf3e11e |
|
MD5 | 87f57f244a8b9116f5f9ba2cceea173b |
|
BLAKE2b-256 | 83cbed05ce9377ce717c01239c266d41ee7108aab622ab460c10b8e293689bc2 |