What is a Pythonic way for Dependency Injection?

后端 未结 9 2110
终归单人心
终归单人心 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条回答
  •  自闭症患者
    2020-12-02 07:44

    Due to Python OOP implementation, IoC and dependency injection are not standard practices in the Python world. But the approach seems promising even for Python.

    • To use dependencies as arguments is a non-pythonic approach. Python is an OOP language with beautiful and elegant OOP model, that provides more straightforward ways to maintain dependencies.
    • To define classes full of abstract methods just to imitate interface type is weird too.
    • Huge wrapper-on-wrapper workarounds create code overhead.
    • I also don't like to use libraries when all I need is a small pattern.

    So my solution is:

    # Framework internal
    def MetaIoC(name, bases, namespace):
        cls = type("IoC{}".format(name), tuple(), namespace)
        return type(name, bases + (cls,), {})
    
    
    # Entities level                                        
    class Entity:
        def _lower_level_meth(self):
            raise NotImplementedError
    
        @property
        def entity_prop(self):
            return super(Entity, self)._lower_level_meth()
    
    
    # Adapters level
    class ImplementedEntity(Entity, metaclass=MetaIoC):          
        __private = 'private attribute value'                    
    
        def __init__(self, pub_attr):                            
            self.pub_attr = pub_attr                             
    
        def _lower_level_meth(self):                             
            print('{}\n{}'.format(self.pub_attr, self.__private))
    
    
    # Infrastructure level                                       
    if __name__ == '__main__':                                   
        ENTITY = ImplementedEntity('public attribute value')     
        ENTITY.entity_prop         
    

    EDIT:

    Be careful with the pattern. I used it in a real project and it showed itself a not that good way. My post on Medium about my experience with the pattern.

提交回复
热议问题