[FIXED] How does Python add Typing hints to classes?

Issue

There is such a demand, I have a create_connnection function, the conn_constructor can be any one of SqlLiteConnection, PGsqlConnection, MysqlConnection, etc.

What typing hints can I add to the conn_constructor parameter to implement, what class is the parameter, and what class is the return value an instance of?

Obviously, Any is not a good thing, because the code completion of the IDE is lost

from typing import TypeVar, Generic
from abc import abstractclassmethod
from typing import Any


class BaseConnection:
    @abstractmethod
    def connect(self):
        pass


class MysqlConnection(BaseConnection):
    def connect(self):
        pass


class PGsqlConnection(BaseConnection):
    def connect(self):
        pass


class SqlLiteConnection(BaseConnection):
    def connect(self):
        pass


def create_connnection(conn_constructor: Any) -> Any:
    return conn_constructor()


if __name__ == '__main__':
    connection = create_connnection(conn=SqlLiteConnection)

Solution

You can use a TypeVar

from abc import abstractmethod
from typing import Type, TypeVar


class BaseConnection:
    @abstractmethod
    def connect(self):
        pass


class MysqlConnection(BaseConnection):
    def connect(self):
        pass


class PGsqlConnection(BaseConnection):
    def connect(self):
        pass


class SqlLiteConnection(BaseConnection):
    def connect(self):
        pass


ConnT = TypeVar("ConnT", bound=BaseConnection)


def create_connnection(conn_constructor: Type[ConnT]) -> ConnT:
    return conn_constructor()


if __name__ == '__main__':
    connection = create_connnection(SqlLiteConnection)

See it working https://mypy-play.net/?mypy=latest&python=3.10&gist=1afc3a41adf2ca4be75d6273b9d26c0d



Answered By - Anentropic
Answer Checked By - Gilberto Lyons (Python.Easybugfix Admin)

Related Posts

Post a Comment