如何在Python中正确检查对象类型?

Pao*_*olo 3 python comparison types isinstance

问题:我必须检查返回的值是否为Python字典.

Q1.这些选项中的哪一个是正确的方法?

type(x) == dict

type(x) == type(dict)

isinstance(d, dict)
Run Code Online (Sandbox Code Playgroud)

然后有其他变体使用is运算符而不是==.

Q2.许多人说检查对象的类型通常是一种不好的做法,但对于我最初的问题,我还有其他选择吗?

S.L*_*ott 8

Q1.这些选项中的哪一个是正确的方法?

不要在类型检查上浪费时间.

它容易出错,因为它基于假设.

Q2.......我还有其他选择吗?

是的,这样做.

try:
    x.the_dict_operation()
except TypeError:
    # x was not the expected type for the operation
    raise # or whatever.
Run Code Online (Sandbox Code Playgroud)

在大多数情况下,这相当于"什么都不做".

只需编写代码即可.如果"某种程度上"恶意的反社会人员使用了错误的类型,它就会像它应该的那样崩溃.