What is a Pythonic way for Dependency Injection?

后端 未结 9 2143
终归单人心
终归单人心 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:42

    Dependency injection is a simple technique that Python supports directly. No additional libraries are required. Using type hints can improve clarity and readability.

    Framework Code:

    class UserStore():
        """
        The base class for accessing a user's information.
        The client must extend this class and implement its methods.
        """
        def get_name(self, token):
            raise NotImplementedError
    
    class WebFramework():
        def __init__(self, user_store: UserStore):
            self.user_store = user_store
    
        def greet_user(self, token):
            user_name = self.user_store.get_name(token)
            print(f'Good day to you, {user_name}!')
    

    Client Code:

    class AlwaysMaryUser(UserStore):
        def get_name(self, token):      
            return 'Mary'
    
    class SQLUserStore(UserStore):
        def __init__(self, db_params):
            self.db_params = db_params
    
        def get_name(self, token):
            # TODO: Implement the database lookup
            raise NotImplementedError
    
    client = WebFramework(AlwaysMaryUser())
    client.greet_user('user_token')
    

    The UserStore class and type hinting are not required for implementing dependency injection. Their primary purpose is to provide guidance to the client developer. If you remove the UserStore class and all references to it, the code still works.

提交回复
热议问题