作成日 2026年2月1日日曜日
更新日 2026年2月1日日曜日
if foo == True:
print("foo is True.")
if foo:
print("foo is True")
明示的に True との比較をしたいときは
if foo is True:
print("foo is True")
と書く(この例はあまりよくない)
None と同じように True や False も比較に is を使うべきかわからなかったので調べた。
結論としては Python の真偽値は None と同様にシングルトン(singleton)であるので、比較に is を使うことができる。
ただし、冒頭のように書くような場合はそもそも真偽値の比較をすべきではない。
PEP 285 には
The values False and True will be singletons, like None. Because the type has two values, perhaps these should be called “doubletons”? The real implementation will not allow other instances of bool to be created.
と書かれていて None と同様に True と False も同一の実行中はひとつのインスタンスしか持たない。
そして、PEP 8 には
Comparisons to singletons like None should always be done with is or is not, never the equality operators.
とあるので、比較するときは等価演算子 == ではなく is や is not を使う。
また、同じく PEP 8 に
Don’t compare boolean values to True or False using ==:
# Correct: if greeting:# Wrong: if greeting == True:Worse:
# Wrong: if greeting is True:
とあるので、そもそも比較演算子を用いた比較自体を行うべきではない。