[FIXED] how to annotate a python 3 factory method that returns an object of a child class?

Issue

I am trying to write a factory method that returns an instance of a dynamic class inheriting from an abstract class. The factory works, but I do not know how to annotate properly the methods:

class ClientBase(ABC):
    @abstractmethod
    def __init__(self, connection: Connection):
        self._connection = connection

class BuildClient(ClientBase):
    def __init__(self, connection: Connection):
        super().__init__(connection)

def _get_client(full_class_name: str, connection) -> ???:
    def _get_class(full_class_name: str) -> ???:
        module_name, class_def = (__package__ + full_class_name).rsplit('.', 1)
        imported = import_module(module_name)
        return getattr(imported, class_def)

    client_class = _get_class(full_class_name)
    return client_class(connection)

class ClientFactory:
    def __init__(self, connection: Connection):
        self._connection = connection

    def get_client(self, client_type: str) -> ???:
        full_class_name = f'.{client_type}.{client_type}_client.{client_type.capitalize()}Client'
        return _get_client(full_class_name, self._connection)

What I do not know to express is the annotations for ClientFactory.get_client and _get_client (also it's internal method). I can annotate the return types for _get_client and _get_class as

def _get_client(full_class_name: str, connection) -> ClientBase:
    def _get_class(full_class_name: str) -> Type[ClientBase]:

and they pass the static checker (of PyCharm), but then I do not know how to annotate the return type of get_client, given that it can come from a number of classes (note that full_class_name gets created on the fly).

Any ideas? Is this possible, at all?


Solution

Imagine, if you were writing this in a strongly typed language like C++ or Java, the return type of get_client() would be ClientBase. If the caller needs to cast to a more specific type, the language allows them to do that (in Python you would use typing.cast()).

Tangentially, I would generally argue that the caller shouldn't need to know the type more specifically than ClientBase, but that's not the topic of this question, so I guess I'll leave it at that.



Answered By - TallChuck
Answer Checked By - Pedro (Python.Easybugfix Volunteer)

Related Posts

Post a Comment