Python Dependency Injection Framework

2019-01-21 02:03发布

Is there a framework equivalent to Guice (http://code.google.com/p/google-guice) for Python?

16条回答
The star\"
2楼-- · 2019-01-21 02:05

There is a somewhat Guicey python-inject project. It's quite active, and a LOT less code then Spring-python, but then again, I haven't found a reason to use it yet.

查看更多
我命由我不由天
3楼-- · 2019-01-21 02:06

Here is a small example for a dependency injection container that does constructor injection based on the constructor argument names:

http://code.activestate.com/recipes/576609-non-invasive-dependency-injection/

查看更多
小情绪 Triste *
4楼-- · 2019-01-21 02:06

Simpler than a framework is the @autowired decorator.

This decorator provides clean dependency injection and lazy initialization support.

It turns code like this:

def __init__(self, *, model: Model = None, service: Service = None):
    if model is None:
        model = Model()

    if service is None:
        service = Service()

    self.model = model
    self.service = service
    # actual code

into this:

@autowired
def __init__(self, *, model: Model, service: Service):
    self.model = model
    self.service = service
    # actual code

It isn't a framework, so you there is zero setup and enforced workflows, though it doesn't provide injection contexts manipulation.

Disclosure: I'm the project maintainer.

查看更多
劳资没心,怎么记你
5楼-- · 2019-01-21 02:09

pinject (https://github.com/google/pinject) is a newer alternative. It seems to be maintained by Google and follows a similar pattern to Guice (https://code.google.com/p/google-guice/), it's Java counterpart.

查看更多
Viruses.
6楼-- · 2019-01-21 02:13
别忘想泡老子
7楼-- · 2019-01-21 02:14

There's dyject (http://dyject.com), a lightweight framework for both Python 2 and Python 3 that uses the built-in ConfigParser

查看更多
登录 后发表回答