Python - 检查签名注释是否是特定的 class

Python - Check if signature annotation is of specific class

使用时

for sig in inspect.signature.parameters.items():
    if isinstance(sig[1].annotation, inspect._empty):
        print("empty")

我从来没有让控制台说打印 "empty"。即使在使用

print(sig[1].annotation)

在 if 子句给我输出之前:<class 'inspect._empty'>。 我也试过像这样使用字符串比较:

if sig[1].annotation == "<class 'inspect._empty'>":
    print("empty")

这里的问题在哪里?

不要使用isinstance,只需检查is inspect._empty,即:

for sig in inspect.signature.parameters.items():
    if sig[1].annotation is inspect._empty:
        print("empty")

或者最好使用已记录的 Signature.emptyParameter.empty。它们都是一样的,但尽量避免使用受保护的属性,即以 _.

开头的属性