Python 类型提示的未知变量

Unknown variable for Python typehint

我有一个包装函数,如果要 return 编辑的变量未知,我应该将什么作为 return 值?

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}:

看起来您可以使用 Any 类型。 https://docs.python.org/3/library/typing.html#typing.Any

通过将 func_to_call 定义为 Callable that returns some Generic type, you can then say that try_catch_in_loop will also return that type. You would express this using 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:
    ...