PythonにおけるNoneの判定
PythonにおいてNone
は値が存在しないことを表す組み込み定数。None
と判定するにはis None
やis not None
とする。
なお、非数を表すnan
は浮動小数点数float
型の値でNone
とは別物。nan
についての詳細は以下の記事を参照。
- 関連記事: Pythonにおけるnanの判定
PythonにおけるNone
PythonにおけるNone
はNoneType
型のオブジェクト。
a = None
print(a)
# None
print(type(a))
# <class 'NoneType'>
値が存在しないことを表し、例えばreturn
で明示的に値を返さない関数はNone
を返す。
def func_none():
# do something
pass
x = func_none()
print(x)
# None
Noneの判定: "is None", "is not None"
Pythonのコーディング規約PEP8で推奨されているように、ある変数がNone
であるか、None
でないかの判定にはis None
, is not None
を使う。
None
のようなシングルトンと比較をする場合は、常にis
かis not
を使うべきです。絶対に等値演算子を使わないでください。 プログラミングに関する推奨事項 — pep8-ja 1.0 ドキュメント
a = None
print(a is None)
# True
print(a is not None)
# False
None
はシングルトン(NoneType
型の唯一のインスタンス)なので、値の比較(==
, !=
)は不要で、オブジェクト同一性の比較(is
, is not
)で判定できる。
- 関連記事: Pythonの==演算子とis演算子の違い
None は単量子 (singleton) なので、オブジェクトの同一性テスト (C では ==) を使うだけで十分だからです。 None オブジェクト — Python 3.11.3 ドキュメント
==
や!=
でNone
と比較したり、変数自体をNone
でないことを表す条件式として使ったりすることは避けたほうがよい。以下、その理由を述べる。
==や!=に対するNone
==
や!=
でNone
と比較してもis
, is not
と同じ結果となる。
a = None
print(a == None)
# True
print(a != None)
# False
しかし、==
, !=
は特殊メソッド__eq__
, __ne__
でオーバーロード可能であり、自由にカスタマイズできる。
したがって、__eq__
の実装によっては== None
はNone
でない値に対してもTrue
を返す可能性がある。is None
は常に正しく判定される。
class MyClass:
def __eq__(self, other):
return True
my_obj = MyClass()
print(my_obj == None)
# True
print(my_obj is None)
# False
Noneの真偽値判定
Pythonではすべてのオブジェクトが真偽値(True
またはFalse
)として判定される。
None
はFalse
と判定される。
print(bool(None))
# False
しかし、ある変数x
がNone
でないという条件分岐をif x
と書いてはいけない。0
を表す数値や空文字、空のリストなどもFalse
と判定されるので、None
と区別できない。
a = None
if a:
print(f'{a} is not None')
else:
print(f'{a} is None')
# None is None
a = 0
if a:
print(f'{a} is not None')
else:
print(f'{a} is None')
# 0 is None
ここでもx is not None
を使うべきである。
a = None
if a is not None:
print(f'{a} is not None')
else:
print(f'{a} is None')
# None is None
a = 0
if a is not None:
print(f'{a} is not None')
else:
print(f'{a} is None')
# 0 is not None