Jeff Heuang
Jeff Heuang

Reputation: 23

In python, how to check two object have the same attribute values when the objects could possible be None?

I have two objects and I want to check if they have the same attribute values. But the objects could be None. I have the following code. Other than that, could it be simpler to do the same job?

    if obj1 is None and obj2 is None:
        return True

    if obj1 is None and obj2 is not None:
        return False

    if obj1 is not None and obj2 is None:
        return False

    if obj1.val != obj2.val:
        return False

Upvotes: 2

Views: 501

Answers (2)

ggorlen
ggorlen

Reputation: 56905

The whole thing boils down to:

if obj1 is None or obj2 is None:
    return obj1 is obj2 # we know at least one is None; are they both None?

return obj1.val == obj2.val # both are definitely not None, compare vals

Test it:

>>> def eq(a, b): return a is b if a is None or b is None else a.val == b.val
... 
>>> from collections import namedtuple
>>> Node = namedtuple("Node", "val")
>>> eq(Node(1), Node(1))
True
>>> eq(Node(1), Node(2))
False
>>> eq(Node(2), None)
False
>>> eq(None, None)
True
>>> eq(None, Node(1))
False

As a practical application, this can be used as part of a recursive algorithm in determining whether two binary trees are the same, as in Leetcode: Same Tree. This might explain why your last condition, the obj1.val == obj2.val case, is missing, because that's your recursive case.

Upvotes: 6

Reinderien
Reinderien

Reputation: 15231

For the middle two comparisons,

if obj1 is None and obj2 is not None:
    return False

if obj1 is not None and obj2 is None:
    return False

can be reduced to

if (obj1 is None) != (obj2 is None):
    return False

In other words, establish two boolean values representing none-ness, and then compare those values to each other.

Upvotes: 1

Related Questions