繁体   English   中英

如何检查 Callable 的返回类型

[英]How to inspect return type of Callable

假设我有以下内容:

import inspect
from collections.abc import Callable  # Using Python 3.10+
from typing import get_type_hints

def foo(arg: Callable[..., int]) -> None:
    pass

type_hints = get_type_hints(foo)["arg"]
annotation = inspect.signature(foo).parameters["arg"].annotation
# How can one get the return type `int` from either of these?

我可以弄清楚如何获得Callable类型提示。 从那里,如何检查Callable的返回类型?

为了避免访问 dunder 属性,这通常是不安全的并且可能会在版本之间中断,您应该使用 通过typing module 提供的方法

type_hint = get_type_hints(foo)["arg"]
arg_types, return_type = get_args(type_hint)

这适用于任何Callable arg_typesEllipsis ( ... ) 或 args list (也可能是typing.ParamSpectyping.Concatenate ,如果您使用它们), return_type 是占据第二位的任何内容。

annotation.__args__

or

type_hints.__args__

(Ellipsis, <class 'int'>)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM