Reputation: 1851
I'm wondering how to quickly see if all objects in a list have an attribute set to a certain value, and if so run a portion of code. So far, in any program that I've written that needs this, I've done something similar to the code below.
listOfObjects = []
class thing():
def __init__(self):
self.myAttribute = "banana"
listOfObjects.append(self)
def checkStuff():
doSomething = True
for i in listOfObjects:
if i.myAttribute != "banana":
doSomething = False
if doSomething: print("All bananas, sir!")
What I'm looking for is something like:
if listOfObjects.myAttribute == "banana":
print("All bananas, sir!")
Upvotes: 1
Views: 1622
Reputation: 117866
You could use a generator expression in the all
function.
def checkStuff():
doSomething = all(i.myAttribute == 'banana' for i in listOfObjects)
if doSomething: print("All bananas, sir!")
Upvotes: 7
Reputation: 375475
I think I would just you a generator expression (and getattr):
all(getattr(item, "myAttribute", False) == "banana" for item in listOfObjects)
This has the potential benefit of not raising if item doesn't have a myAttribute attribute.
Note: My original answer checked that all items had the attribute "banana" with hasattr:
all(hasattr(item, "banana") for item in listOfObjects)
Upvotes: 2