Search code examples
pythonlinuxuniquemembership

Test if all objects have same member value


I have a simple class in :

class simple(object):
    def __init__(self, theType, someNum):
        self.theType = theType
        self.someNum = someNum

Later on in my program, I create multiple instantiations of this class, i.e.:

a = simple('A', 1)
b = simple('A', 2)
c = simple('B', 3)
d = simple('B', 4)
e = simple('C', 5)

allThings = [a, b, c, d, e] # Fails "areAllOfSameType(allThings)" check

a = simple('B', 1)
b = simple('B', 2)
c = simple('B', 3)
d = simple('B', 4)
e = simple('B', 5)

allThings = [a, b, c, d, e] # Passes "areAllOfSameType(allThings)" check

I need to test if all of the elements in allThings have the same value for simple.theType. How would I write a generic test for this, so that I can include new "types" in the future (i.e. D, E, F, etc) and not have to re-write my test logic? I can think of a way to do this via a histogram, but I figured there's a "pythonic" way to do this.


Solution

  • Just compare each object with the first item's type, using the all() function:

    all(obj.theType == allThings[0].theType for obj in allThings)
    

    There will be no IndexError if the list is empty, too.

    all() short-circuits, so if one object is not the same type as the other, the loop breaks immediately and returns False.