如何在Python中根据函数的返回类型创建类型

0 投票
0 回答
26 浏览
提问于 2025-04-12 10:04

我在用一个没有任何占位符的库。

所以我自己为它创建了一个占位符,但现在我在使用这些我为占位符创建的类型时遇到了问题,因为它们不是原始库的一部分,我无法导入它们。

这里有个例子。

这是我的占位符:

class IdInfoTuple(NamedTuple):
    custom: bool
    chart_mode: int
    select: bool
    visible: bool


def id_info(id: str, /) -> Optional[IdInfoTuple]:

现在在我的代码中,我需要传递IdInfoTuple,但我做不到。

比如当我创建一个这样的函数:

def some_func(idInfo:<how to tell this is type of IdInfo?>):
   pass

我想如果能像TypeScript那样,根据函数的返回类型创建一个类型就好了。

type IdInfoTuple= ReturnType<typeof id_info>;

但我找不到在Python中怎么做。这样做可能吗?如果可以,怎么实现?我希望能帮助pylance找到正确的类型。我不是想在执行时找类型,而是在编码时帮助我更好地定义函数的类型。

0 个回答

暂无回答

撰写回答