【问题标题】:Unknown variable for Python typehintPython类型提示的未知变量
【发布时间】:2018-08-13 19:00:13
【问题描述】:

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

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(...) -&gt; {What do I put here}:

【问题讨论】:

    标签: python-3.x type-hinting pep


    【解决方案1】:

    通过将func_to_call 定义为返回一些Generic 类型的Callable,然后您可以说try_catch_in_loop 也将返回该类型。您可以使用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:
        ...
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-17
        • 2013-09-28
        • 1970-01-01
        • 2010-12-21
        • 1970-01-01
        • 2019-03-22
        • 2010-12-20
        • 2013-12-26
        相关资源
        最近更新 更多