如何使用另一个函数的返回类型来注释Python函数?

ig-*_*nyk 6 python types type-hinting python-3.x

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

def f(a: int) -> List[Tuple(int, float)]
def g(a: List[int]) -> List[decltype(f)]
Run Code Online (Sandbox Code Playgroud)

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

def g(a: List[int])->f.__annotations__['return']
Run Code Online (Sandbox Code Playgroud)

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

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

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

Jim*_*ard 7

当前没有类似的东西存在,并且跟踪器上的输入问题似乎表明它是有计划的.我们随时欢迎您创建一个问题,看看它是如何受欢迎的.

目前你的方法做的伎俩(即分配型),我会介绍将使用唯一的变化get_type_hintstyping,而不是抓住__annotations__直接属性.加上.get(因为它返回一个字典),也可以缩短它:

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

def g() -> return_type(f):
Run Code Online (Sandbox Code Playgroud)

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

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

def return_type(f):
    try:
        return get_type_hints(f).get('return', Any)
    except TypeError:
        return Any
Run Code Online (Sandbox Code Playgroud)

当然,因为动态分配类型,你不能指望静态类型检查器捕获它,你需要静态提示.

  • 这似乎不适用于当前的静态分析工具。 (2认同)