TGViewer
Machine Learning with Python Machine Learning with Python @codeprogrammer · 68.6K subscribers
Post #4788 3.8K

Forwarded from Remote Jobs — Daily LinkedIn Picks 💼

Stop using if obj == None, use if obj is None

In Python, when you write:

obj == None


you're not directly checking if obj is the value None. Instead, you're asking if the object is equal to None.

Yes, in many cases, the result will be the same as for the code:

obj is None


But the behavior of these two variants is different, and this difference is important.

When you use:

obj == None


Python calls the __eq__ method on the object. That is, the object itself decides what it means to be "equal to None". And this method can be overridden.

If obj is an instance of a class in which __eq__ is implemented so that when compared with None, it returns True (even if the object is not actually None), then obj == None may mistakenly give True.

Example:

class Weird:
    def __eq__(self, other):
        return True  # Always asserts that it's equal

obj = Weird()

print(obj == None)  # True
print(obj is None)  # False


Here, it can be seen that obj == None returns True due to the custom behaeqf the __eq__ operator in the class.

Therefore, when using obj == None, the result is not always predictable.

On the other hand, when you write:

obj is None


you're using the is operator, which cannot be overridden. This means that the result will always be the same and predictable.

The is operator checks the identity of objects, that is, whether two references point to the same object. Since None is a singleton (the only instance), obj is None is the correct and most efficient way to perform such a check.

❤️ Therefore, it is always recommended, and this is best practice, to use obj is None instead of obj == None for predictability and efficiency.

👉 https://t.me/DataScienceQ
  • ❤ 8
More from @codeprogrammer
  1. Oct 7, 2026A distinctive bot for subscribing to courses on the most popular educational platforms acr…
  2. Oct 7, 2026Understanding algorithms changes the way you write code. 🧠 This playlist teaches you exac…
  3. Oct 6, 2026🛠 Built an AI app with Cursor, Claude Code or Lovable? Publish it on Zibby (zibby.run), a…
  4. Oct 5, 2026🚀 ChatGPT Plus & Gemini AI Pro🤖 ChatGPT Plus — 1 Month: $8 ✨ Gemini AI Pro — 18 Months:…
  5. Oct 4, 2026I found a great resource for interactive learning about machine learning and AI – VizLearn…
  6. Oct 3, 2026This channels is for Programmers, Coders, Software Engineers. 0️⃣ Python 1️⃣ Data Science…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →