如何输入带有其他函数的函数的 return 值

How to typehint the return value of a function that takes other functions

我有一个接受其他函数的函数,并且想输入提示这个“包装器”函数的 return 值。该功能类似于下面的功能,但具有更多特定于用例的逻辑。也就是说,这个功能也很方便:

def guard(func, default: WhatGoesHere = None) -> Optional[WhatGoesHere]:
    try:
        return func()
    except:
        return default

函数是这样使用的,使用现有的类型提示函数以及偶尔的 lambda:

def difficult_math() -> int:
    return e^(pi * i) / 0

if res := guard(difficult_math):
   ...

if res := guard(lambda: x/3):
   ...

像这样

from typing import Callable, Optional, TypeVar

R = TypeVar('R')

def guard(func: Callable[[], R], default: R = None) -> Optional[R]:
    try:
        return func()
    except:
        return default

如果您的函数需要 *args, **kwargs,您可以使用 ParamSpec 扩展它。以及您想要包含的其他位置参数 Concatenate.