首页 > 解决方案 > Python类型提示的未知变量

问题描述

我有一个包装函数,如果要返回的变量未知,我应该把什么作为返回值?

def try_catch_in_loop(func_to_call: callable, *args):
    for attempt in range(NUM_RETRYS + 1):
        try:
            if attempt < NUM_RETRYS:
                return func_to_call(*args)
            else:
                raise RunTimeError("Err msg")
        except gspread.exceptions.APIError:
            request_limit_error()

专门查看在函数调用末尾放置的内容,即:

def try_catch_in_loop(...) -> {What do I put here}:

标签: python-3.xtype-hintingpep

解决方案


通过定义func_to_call为 aCallable返回某种Generic类型,您可以说它也try_catch_in_loop将返回该类型。您可以使用 a 来表达这一点TypeVar

from typing import Callable, TypeVar

return_type = TypeVar("return_type")

def try_catch_in_loop(func_to_call: Callable[..., return_type], *args) -> return_type:
    ...

推荐阅读