在 python 3.8 中区分 1 和 True

问题描述 投票:0回答:2

我有一些代码,如果特定的输入变量是 1 与 True,我想做不同的事情。 (简而言之,数字指的是对几个对象中的哪一个执行某项操作,True 表示对所有对象执行该操作,但这与这个问题并不特别相关。)

目前,我使用的或多或少相当于:

if x is True:
   # Do something
elif x is 1:
   # Do something else
else:
   # More possibilities follow...

但是在 Python 3.8 中,我现在得到了

SyntaxWarning: "is" with a literal. Did you mean "=="?

嗯,不,我没有。使用

==
并不能区分
True
1
,因为 python 中的
True == 1

但听起来 python 开发者认为使用

is
和文字是总是一个错误。这只是一个警告,而不是一个错误,所以我现在还好,但是我应该切换到什么是无错误的方法?

python python-3.8
2个回答
3
投票

我想我已经明白了。 (很抱歉回答我自己的问题。)

事实证明,警告只是在整数上,而不是在

True
上。好像写
if x is True
还可以,但是写不
if x is 1
。一旦排除了前一种可能性,后者就可以安全地使用
==

所以我认为正确的形式是

if x is True:
   # Do something
elif x == 1:
   # Do something else
else:
   # More possibilities follow...

0
投票

也许比混合方法更干净的是显式测试类型

>>> type(1) == bool
False
>>> type(1) == int
True
>>>
>>> type(True) == bool
True
>>> type(True) == int
False
© www.soinside.com 2019 - 2024. All rights reserved.