#python #python-3.x #python-typing
#python #python-3.x #python-типизация
Вопрос:
У меня ситуация, когда у меня есть два удобных метода для поиска и инициализации классов из точки входа, и я хочу отличить то, что они делают друг от друга.
Ниже приведена упрощенная версия моей проблемы
class ToBeExtended:
""" Abstract base class that is to be extended """
pass
def find(classname: str) -> ToBeExtended:
""" Find the class definition of the class named `classname` from the entry points """
... # Get the class
return ClassDefinition
def connect(classname: str, *args, **kwargs) -> ToBeExtended:
""" Find and initialise the class with the passed arguments and return """
return find(classname)(*args, **kwargs)
find
в этом примере возвращается объект класса, а не экземпляр.
Есть ли способ обернуть это, чтобы передать этот контекст линтеру / пользователю?Похоже, в нем ничего нет typing
, и я бы хотел, чтобы класс был идентифицируемым, ничего подобного -> type:
Ответ №1:
import typing
class ToBeExtended:
""" Abstract base class that is to be extended """
pass
def find(classname: str) -> typing.Type[ToBeExtended]:
""" Find the class definition of the class named `classname` from the entry points """
... # Get the class
return ClassDefinition
def connect(classname: str, *args, **kwargs) -> ToBeExtended:
""" Find and initialise the class with the passed arguments and return """
return find(classname)(*args, **kwargs)