Search code examples
pythonlistclassdictionarylist-comprehension

Is there a simple way to compare two class objects for all items that are not none?


I am looking to compare two instances of the same class, but only the items for which both are not None.

for instance,

I will have a Bolt class, and one instance will have:

bolt1.locx = 1.0
bolt1.locy = 2.0
bolt1.locz = 3.0
bolt1.rpid = 1234
bolt1.nsid = [1,2,3,4]

bolt2.locx = 1.0
bolt2.locy = 2.0
bolt2.locz = 3.0
bolt2.rpid = None
bolt2.nsid = None

In this case, I want to compare these classes as true.

I know I can use the __dict__ of each class to iterate through the attributes, but I was wondering if this is something that could be a list comprehension.


Solution

  • I would just keep it simple:

    class Bolt:
        # ...
    
        def __eq__(self, other):
            if [self.locx, self.locy, self.locz] != [other.locx, other.locy, other.locz]:
                return False
            if self.rpid is not None && other.rpid is not None && self.rpid != other.rpid:
                return False
            if self.nsid is not None && other.nsid is not None && self.nsid != other.nsid:
                return False
            return True