What is a Pythonic way for Dependency Injection?

后端 未结 9 2145
终归单人心
终归单人心 2020-12-02 06:57

Introduction

For Java, Dependency Injection works as pure OOP, i.e. you provide an interface to be implemented and in your framework code accept an instance of a c

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 07:43

    The way we do dependency injection in our project is by using the inject lib. Check out the documentation. I highly recommend using it for DI. It kinda makes no sense with just one function but starts making lots of sense when you have to manage multiple data sources etc, etc.

    Following your example it could be something similar to:

    # framework.py
    class FrameworkClass():
        def __init__(self, func):
            self.func = func
    
        def do_the_job(self):
            # some stuff
            self.func()
    

    Your custom function:

    # my_stuff.py
    def my_func():
        print('aww yiss')
    

    Somewhere in the application you want to create a bootstrap file that keeps track of all the defined dependencies:

    # bootstrap.py
    import inject
    from .my_stuff import my_func
    
    def configure_injection(binder):
        binder.bind(FrameworkClass, FrameworkClass(my_func))
    
    inject.configure(configure_injection)
    

    And then you could consume the code this way:

    # some_module.py (has to be loaded with bootstrap.py already loaded somewhere in your app)
    import inject
    from .framework import FrameworkClass
    
    framework_instance = inject.instance(FrameworkClass)
    framework_instance.do_the_job()
    

    I'm afraid this is as pythonic as it can get (the module has some python sweetness like decorators to inject by parameter etc - check the docs), as python does not have fancy stuff like interfaces or type hinting.

    So to answer your question directly would be very hard. I think the true question is: does python have some native support for DI? And the answer is, sadly: no.

提交回复
热议问题