Hacker News new | ask | show | jobs
by nomel 1022 days ago
‘is’ checks if it the object ids are the same, with None having a unique one. Equals can be tricked.

Here’s a class that is equal to None, and everything else:

    class EqualsEverything:
        def __equals__(self, other: Any) -> bool:
            return True
1 comments

Thanks, I saw this on SO too.

Just curious: would it ever happen in practice?

every little thing happens in practice... usually unnoticed and buried while refactoring something innocent/ly.

sooner or later the __eq__ method will be redefined for some class, then reworked, and then.. == None might not be what was supposed to be..

or, my favorite, x='a' ; (x,)[0] == x[0] == x .. but are only equal until x changes to something not-1-long-sequence..

I try to avoid statistical programming, preferring determinism, driven by intent. ;)

So, I use "is" since "is" is not a context dependent concept, like equals is. I've seen this once in the wild, and it made sense for its use:

    def __eq__(self, other):
        return bool(self) == bool(other)