Skip to main content
siringa logo

Build Status PyPI Coverage Status Documentation Status Stability Python Versions Say Thanks

About

siringa (meaning syringe in Italian) is a minimalist, idiomatic dependency injection and inversion of control library for Python, implemented in Hy, a homoiconic Lisp dialect for Python.

To get started, take a look to the documentation, API, tutorial and examples.

Features

  • Simple, idiomatic and versatile programmatic API.

  • Annotation based dependency injection that is PEP 3017 and PEP 0484 friendly.

  • First-class decorator driven dependency injection and registering.

  • Ability to create multiple dependency containers.

  • Hierarchical dependency containers based on inheritance.

  • Dependency inference based on pattern-matching techniques.

  • First-class support for dependency mocking for better testing.

  • Detects cyclic dependencies (work in progress).

  • Small and (almost) dependency-free library.

  • Works with CPython 3+.

Design philosophy

  • Code instrumentation should be non-intrusive and idiomatic.

  • Explicitness over implicitness: dependencies and injections much be explicitly defined.

  • Python idiomatic: embrace decorators and type annotations.

  • Minimalism: less enables more.

  • Uniformity: there is only one way to declare and consume dependencies.

  • Predictability: developer intentions must persist based on explicitly defined intention.

  • Domain agnostic: do not enforce any domain-specific pattern.

Installation

Using pip package manager:

pip install --upgrade siringa

Or install the latest sources from Github:

pip install -e git+git://github.com/h2non/siringa.git#egg=siringa

Tutorial

Importing siringa

import siringa

Instrumenting dependencies

siringa embraces type hints/arguments annotation Python syntax for dependency inference and pattern matching.

@siringa.inject
def task(x, y, logger: '!Logger'):
    logger.info('task called with arguments: {}, {}'.format(x, y))
    return x * y

You can optionally annotate dependencies via siringa type annotations:

from siringa import A

@siringa.inject
def task(x, y, logger: A('Logger')):
    logger.info('task called with arguments: {}, {}'.format(x, y))
    return x * y

Finally, for a DRYer approach you can simply annotate dependencies with ! annotation flag.

In this case, the argument name expression will be used for dependency inference.

from siringa import A

@siringa.inject
def task(x, y, Logger: '!'):
    Logger.info('task called with arguments: {}, {}'.format(x, y))
    return x * y

Registering dependencies

siringa allows you to rely on decorators for idiomatic dependencies registering.

Dependency name is dynamically inferred at registration time based on class or function name.

@siringa.register
class Logger(object):
    logger = logging.getLogger('siringa')

    @staticmethod
    def info(msg, *args, **kw):
        logger.info(msg, *args, **kw)

However, you can define a custom dependency name by simply passing a string as first argument:

@siringa.register('MyCustomLogger')
class Logger(object):
    ...

Finally, you can register dependencies with a traditional function call, such as:

class Logger(object):
    pass

siringa.register('MyCustomLogger', Logger)

class compute(x, y):
    return x * y

siringa.register('multiply', compute)

Invocation

siringa wraps callable object in the transparent and frictionless way abstracting things for developers.

You can invoke or instantiate any dependency injection instrumented object as you do traditionally in raw Python code and siringa will do the rest for you inferring and pattern-matching required dependencies accordingly for you.

Below is an example of how simple it is:

# Call our previously declared function in this tutorial.
# Here, siringa will transparently inject required dependencies accordingly,
# respecting the invokation arguments and order.
task(2, 2) # => 4

Let’s demostrate this with a featured example:

import siringa

@siringa.register
def mul(x, y):
    return x * y

@siringa.register
def mul2(x, mul: '!mul'):
    return mul(x, 2)

@siringa.register
def pow2(x):
    return x ** 2

@siringa.inject
def compute(x, pow: '!pow2', mul: '!mul2'):
    return pow(mul(x))

compute(2) # => 16

You can also use the invocation API in case that the target object was not properly instrumented as dependency:

@siringa.register
def mul2(x):
    return x * 2

# Note that the function was not instrumented yet!
def compute(x, mul: '!mul2'):
    return mul(x)

siringa.invoke(compute, 2)

Create a new dependency container

siringa provides a built-in global dependency container for usability purposes, but you can create as much containers as you want.

In the siringa idioms, this means creating a new dependency layer which provides its own container and dependency injection API, pretty much as the global package API.

You can create a new dependencies layer such as:

layer = siringa.Layer('app')

# Then you can use the standard API
layer.register('print', print)

# Then you can use the standard API
@layer.inject
def mul2(x, print: '!'):
    print('Argument:', x)
    return x * 2

mul2(x)

A dependency layer can inherit from a parent dependency layer.

This is particularly useful in order to create a hierarchy of dependency layers where you can consume and inject dependencies from a parent container.

parent = siringa.Layer('parent')
child = siringa.Layer('child', parent)

# Register a sample dependency within parent
@parent.register
def mul2(x):
    return x * 2

# Verify that the dependency is injectable from child layer
parent.is_injectable('mul2') # True
child.is_injectable('mul2') # True

@child.inject
def compute(x, mul: '!mul2'):
    return mul(x)

compute(2) # => 2

Mocking dependencies

siringa allows you to define mocks for dependencies, which is particularly useful during testing:

@siringa.register
class DB(object):
    def query(self, sql):
        return ['john', 'mike']

@siringa.mock('DB')
class DBMock(object):
    def query(self, sql):
        return ['foo', 'bar']

@siringa.inject
def run(sql, db: '!DB'):
    return db().query(sql)

# Test mock call
assert run('SELECT name FROM foo') == ['foo', 'bar']

# Once done, clear all the mocks
siringa.unregister_mock('DB')

# Or alternatively clear all the registed mocks within the container
siringa.clear_mocks()

# Test read call
assert run('SELECT name FROM foo') == ['john', 'mike']

History

v0.1.3 / 2017-04-25

  • fix(invoke): missing export symbol at public level

  • refactor(docs): update disclaimer note

  • fix(docs): remove unused tutorial.rst file

  • refactor(Makefile): use –commit when bumping version

v0.1.2 / 2017-04-25

  • feat(examples): add inject flag example

  • fix(injector): process inject flag “!” based annotations accordingly

  • fix(register): return decorated injectable callable object, if needed

  • fix(register): return decorated injectable callable object, if needed

  • refactor(analyzer): use method access notation

  • refactor(docs): typo in design philosophy section

  • fix(docs): typo in rst syntax

  • fix(examples): type on mocking example comment

v0.1.1 / 2017-04-24

  • fix(core): handle not present __init__ member in classes. feat(examples): add mocking example

  • fix(docs): type in about section

  • fix(setup.py): package description

v0.1.0 (2017-04-23)

  • First version (beta).

Metadata

Release files for siringa 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for siringa 0.1.3
File Size Uploaded
siringa-0.1.3.tar.gz 8.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for siringa 0.1.3
File Interpreter ABI Platform
siringa-0.1.3-py2.py3-none-any.whl Python 3, Python 2 none any Details

Total release size: 25.7 kB

Release files / siringa-0.1.3.tar.gz

Download URL siringa-0.1.3.tar.gz
Size 8.9 kB
Tags Source
SHA-256 checksum
How to use checksums
54f40ce7c3722fcf96d128b2c4e99b8f91124c8cee41b4d2321d1715238e6fb7
BLAKE2b-256 checksum
How to use checksums
b6948d5c6f3855ce0848d6cff7a555ed50bbd0099937c09ae1bfe4a6729c2f06
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / siringa-0.1.3-py2.py3-none-any.whl

Download URL siringa-0.1.3-py2.py3-none-any.whl
Size 16.8 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
698c9951885cdf4b99970dd702232a2a6c34293d1a1d23c02774d609d8d5733d
BLAKE2b-256 checksum
How to use checksums
96013f44bbcf82cb6fdbb4a8b49077301455775e1dea04f62999e4c0228a77bd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release history Release notifications | RSS feed

This release

0.1.3 This release

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page