在 Python 中测试一个类型的正确方法是什么 typing.Dict?

What is the correct way to test a type is bare typing.Dict in Python?

我想写一个函数 is_bare_dict 到 return True for Dict and false for any typed dict such as Dict[int, str].

我能想到的一种方法是这样的:

from typing import Dict, KT, VT

def is_bare_dict(typ) -> bool:
    ktype = typ.__args__[0]
    vtype = typ.__args__[1]
    return ktype is KT and vtype is VT

你可以运行上面的代码:https://wandbox.org/permlink/sr9mGbWo3Lh7VrPh

也可以一行完成

from typing import Dict, KT, VT

def is_bare_dict(typ) -> bool:
    return not isinstance(typ.__args__, tuple)


print(is_bare_dict(Dict)) # Print True
print(is_bare_dict(Dict[int, str])) # Print False
def is_typing_dot_dict(typ) -> bool:
    return typ is typing.Dict

如果你真的想测试某事是否 typing.Dict,那就去做吧。不过,这可能不是要测试的正确对象 - 您似乎也想同样对待 dict,也许 typing.Dict[Any, Any]。 (此外,typing.Dict 已被弃用,可能最终会消失。)