Python Dependency Injection Framework

后端 未结 18 2186
你的背包
你的背包 2020-12-12 14:10

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

18条回答
  •  暖寄归人
    2020-12-12 14:13

    After years using Python without any DI autowiring framework and Java with Spring I've come to realize that plain simple Python code often doesn't need a framework for dependency injection autowiring (autowiring is what Guice and Spring both do in Java), i.e., just doing something like this is enough:

    def foo(dep = None):  # great for unit testing!
        ...
    

    This is pure dependency injection (quite simple) but without magical frameworks for automatically injecting them for you.

    Though as I dealt with bigger applications this approach wasn't cutting it anymore. So I've come up with injectable a micro-framework that wouldn't feel non-pythonic and yet would provide first class dependency injection autowiring.

    Under the motto Dependency Injection for Humans™ this is what it looks like:

    # some_service.py
    class SomeService:
        @autowired
        def __init__(
            self,
            database: Autowired(Database),
            message_brokers: Autowired(List[Broker]),
        ):
            pending = database.retrieve_pending_messages()
            for broker in message_brokers:
                broker.send_pending(pending)
    
    # database.py
    @injectable
    class Database:
        ...
    
    # message_broker.py
    class MessageBroker(ABC):
        def send_pending(messages):
            ...
    
    # kafka_producer.py
    @injectable
    class KafkaProducer(MessageBroker):
        ...
    
    # sqs_producer.py
    @injectable
    class SQSProducer(MessageBroker):
        ...
    

提交回复
热议问题