如何使用另一个函数的返回类型注释 Python 函数? [英] How to annotate Python function using return type of another function?

查看:30
本文介绍了如何使用另一个函数的返回类型注释 Python 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C++ 中寻找一些类似于 decltype 的东西.我想要完成的是以下内容:

I am looking for some analogue of decltype in C++. What I am trying to accomplish is the following:

def f(a: int) -> List[Tuple(int, float)]
def g(a: List[int]) -> List[decltype(f)]

所以想法是使用另一个函数的类型注释.我找到的解决方案看起来有点笨拙:

So the idea is to use type annotation of another function. The solution I found looks somehow clumsy:

def g(a: List[int])->f.__annotations__['return']

基本上,问题是是否存在类似 decltype(或许它应该被称为return_type")之类的东西,或者是否计划在以后的版本中使用它.我还编写了一个小函数来说明此功能的可能用法:

Basically, the question is whether there exists something like decltype (perhaps it should be called "return_type") or whether it's planned in further versions. I have also written a small function that illustrates possible use of this functionality:

def return_type(f: Callable):
   try:
       return get_type_hints(f)['return']
   except(KeyError, AttributeError):
       return Any
def g() -> return_type(f):

UPD 正如 Jim Fasarakis-Hilliard 所建议的,我们也可以使用 get_type_hints 而不是 注释

UPD As was suggested by Jim Fasarakis-Hilliard we can also use get_type_hints instead of annotations

推荐答案

目前不存在类似的问题,输入跟踪器 似乎表明它是计划好的.随时欢迎您提出问题,看看人们对此有何欢迎.

Nothing like that currently exists and no issue on the tracker for typing seem to indicate that it is planned. You're always welcome to create an issue and see how this is welcomed.

目前您的方法可以解决问题(即分配类型),我要介绍的唯一更改是使用 get_type_hints 来自 typing 而不是直接获取 __annotations__ 属性.结合 .get(因为它返回一个字典),也可以使这个更短:

Currently your approach does the trick (that is assigns a type), the only change I'd introduce would be to use get_type_hints from typing rather than grabbing the __annotations__ attribute directly. Coupled with .get (since it returns a dict), could make this shorter, too:

def return_type(f):
    return get_type_hints(f).get('return', Any)

def g() -> return_type(f):

如果您愿意,当然可以将其从函数中删除并在一行中使用.

Which can of course be removed from the function and used in a single line if you're so inclined.

如果向 return_type 提供随机对象的可能性存在,您需要捕获它引发的 TypeError 并返回您的默认 Any>:

If the possibility of random objects being supplied to return_type exits, you'll need to catch the TypeError it raises and return your default Any:

def return_type(f):
    try:
        return get_type_hints(f).get('return', Any)
    except TypeError:
        return Any

当然,由于这是动态分配类型,您不能指望静态类型检查器来捕获它,因此您需要静态提示.

Of course since this assigns a type dynamically you can't expect static type checkers to catch it, you need static hinting for that.

这篇关于如何使用另一个函数的返回类型注释 Python 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆