【问题标题】:How to dynamically type properties based on method input (Python)如何根据方法输入动态键入属性(Python)
【发布时间】:2022-01-06 09:57:38
【问题描述】:

有没有办法根据某种参数推断模型属性的类型?

我正在尝试键入返回对象列表的方法的返回类型,例如:

{
    "object": "type_depends_on_input_of_method",
    "certainty": 0.8
}

我正在尝试使该方法接受模型并返回特定的返回类型,以便推断“对象”的类型,如下所示:

CT = TypeVar("CT")

class SearchReturnType(TypedDict, CT):
    object: CT
    certainty: float


class SearchInterface:
    T = TypeVar("T")
    @abc.abstractmethod
    def search(self,
               text: str,
               model: Type[T]) -> List[SearchReturnType(Type[T])]:

有没有办法实现这个?

我的理想情况是,当我执行以下操作时,vscode 会识别类型并自动完成应有的工作:

search_interface = SearchInterfac()
search_interface_response = search_interface.search("somethin", Document)
first_document = search_interface_response[0].object --> Automatically recognized as a Document

【问题讨论】:

  • 我认为你只是继承自 typing.Generic[CT] 而不是 CT
  • 行得通!谢谢

标签: python pydantic


【解决方案1】:

继承自 Generic[CT] 而不是 CT

class SearchReturnType(TypedDict, Generic[CT]):
    object: CT
    certainty: float

SearchReturnType 不是CT 的一种,而是一种使用 CT 的泛型类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    相关资源
    最近更新 更多