2
2

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における`is`と`==`の本質的な違い

Posted at

概要

Pythonのコードレビューで頻出する指摘の一つが、
is==の誤用によるバグの温床

本稿では、この2つの演算子が何を比較しているのか、なぜ結果が異なるのか、いつどちらを使うべきかを構造的に解説する。


1. 結論:is==の違いとは

演算子 比較対象 具体的意味
== 値の等価性 中身(値)が等しいか
is オブジェクトの同一性 メモリ上の同じ実体かを比較する

2. 例で見る差異

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)  # → True(値が等しい)
print(a is b)  # → False(別のリストインスタンス)

c = None
print(c == None)  # → True
print(c is None)  # → True(この場合、どちらも動くが…)

☠️ 危険な書き方

if x == None:  # 間違いではないが推奨されない

✅ 推奨される書き方

if x is None:  # Pythonicかつ厳密な比較

3. is が必要になるシーン

✅ シングルトンの比較

if x is None:
if y is True:
if flag is NotImplemented:

None/True/False/NotImplementedなどの特殊なオブジェクトis で比較するべき。


4. == が適切なシーン

  • リスト、辞書、カスタムクラスなどの中身を比較したいとき
  • クラスで __eq__() をオーバーライドしている場合
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

p1 = Point(1, 2)
p2 = Point(1, 2)

print(p1 == p2)  # → True
print(p1 is p2)  # → False

5. 実務でのバグパターン例

def check_flag(value):
    if value is 0:
        print("Zero")

is を使って int を比較 → バグの原因

✅ 修正すべき書き方

if value == 0:

よくある誤解と対策

is の方が速いから常に使うべき?

→ ✅ パフォーマンスより意味の正しさが重要is は使う場面が限定される。


None==でいいのでは?

→ ✅ 動作は同じでも、is None の方が明確に意図が伝わる設計


結語

Pythonにおける is== の違いは、
“同じか”ではなく、“同じものか”と“同じ中身か”という次元の違いである。

  • is = オブジェクトのIDレベルでの同一性
  • == = 定義された等価性(値や内容)

構造の明快さと意図の明示性こそが、設計としてのPythonicである。

2
2
0

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?