4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】Noneの判定に == や != を使うのはやめよう

Posted at

✅ 結論

None の判定には ==!= ではなく、
必ず is / is not を使いましょう!


🎯 背景:こんな問題がありました

l = [1, 2, None, 3]

# 以下のように出力したい 
1 2 10000 3

❌ よくある間違い

for i in l:
    if i == None:  # ← 一見よさそうだけど…
        i = 10000
    print(i, end=" ")

→ 一部のケースでは正しく動かないことがあります。


✅ 正しい書き方

for i in l:
    if i is None:
        i = 10000
    print(i, end=" ")

🤔 なぜ == None はNGなの?

Pythonでは ==!= の挙動をクラス側でカスタマイズ(オーバーロード)できます。

少し深掘ると以下のようなことです。

  • __eq____ne__==!=の挙動のカスタマイズができる
  • そのカスタマイズによってNoneじゃないのに == None がTrueになることがある!

これは思わぬバグにつながるため、Noneとの比較は常に is / is not を使うのが鉄則です。


🔗 参考リンク


📝 まとめ

比較方法 用途 OK?
a == None 値の等価性 ❌ 避けるべき
a is None オブジェクトの同一性 ✅ 推奨

今後 None を扱うときは、 isを使おうと思いました。

4
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?