Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if all objects have same member value

I have a simple class in python:

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.

like image 263
Cloud Avatar asked Jan 25 '26 22:01

Cloud


1 Answers

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.

like image 127
TerryA Avatar answered Jan 28 '26 13:01

TerryA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!