我怎么知道一个函数将返回哪个类别的值,而无需执行函数本身



这是我的装饰器。我希望任何具有此装饰器的功能是否可以检查_kwargs["_dir_abs"]是否是绝对路径。如果没有,如果装饰的_function返回bool,我想通过返回False来指责_function。如果_function返回CC_7,则返回None

问题是_function是一个文件夹操作(删除,移动,命名...)因此,我不能只是尝试查看它返回的内容。

def check_abs_dec(_function):
    def wrapper(*_args, **_kwargs):
        if not check_abs(_kwargs["_dir_abs"]):
            napw()
            """`return False` if the `_function` return `bool`. `return None`
            if the `_function` return anything other than `bool`.
            """
        return _function(*_args, **_kwargs)
    return wrapper

无论如何,我是否可以在不实际执行的情况下返回什么值_function?有解决方法吗?

您可以尝试使用返回类型来注释您的功能。

def do_not_call() -> bool:  # Note the `-> bool` part
    raise Exception("Do not call, may have side effects")

现在您可以使用__annotations__属性获得返回类型。

print(do_not_call.__annotations__['return'] == bool)  # True
print(do_not_call.__annotations__['return'] == int)  # False
def mysterious():  # Return type is not annotated...
    raise Exception("Do not call this either")
print(mysterious.__annotations__['return'])  # ...so this raises KeyError

这确实需要您注释所有要检查的返回类型的返回类型。

说实话,我也不知道何时将其添加到Python中,但它对我有用的Python 3.5。

如果您是有足够时间的铁杆程序员,我认为您可以使用ast模块检查return语句和猜测类型的函数字节码。我不推荐。

不,您不能按照定义进行此操作。这就是动态语言的工作方式;在执行函数之前,您无法知道将返回哪种类型。

最新更新