检查变量是否是类型的实例或 None

Check if a variable is instance of a type or None

我有一个变量,可以是 intNone。如果是别的,我会报错。

我有以下代码:

if not isinstance(id, int) or id is not None:
    raise AttributeError('must be called with a id of type INT or NONE')

这是行不通的,因为每个条件都否定另一个条件,并且总是会引发错误。

首先,你需要and而不是or

if not isinstance(id, (int, )) and id is not None:
    raise AttributeError('must be called with a id of type INT or NONE')

说明:您正在检查变量是否 both 而不是 int and 而不是 None,因为正如你所说,检查其中一个 另一个总是 True

如果您希望将范围缩小到单张支票,您可以这样做:

if not isinstance(id, (int, type(None))):
    raise AttributeError('must be called with a id of type INT or NONE')

注意:您正在使用该名称隐藏内置 id 函数,请尝试使用不同的函数以避免其他奇怪的错误