Want to be able to provide a search interface for a collection of objects to be used by passing a list of keyword arguments like so:
playerID = players.search(nameFirst='ichiro', nameLast='suzuki')
Where players.search is defined like so:
def search(self, **args):
ret = []
for playerID, player in self.iteritems():
for key, value in args.iteritems():
if getattr(player, key) == value:
ret.append(player.playerID)
return ret
Obviously the above code doesn’t work. I want to, to borrow some SQL idioms, to work like where player.key == value and player.keyN = valueN, and so on for N number of kwargs passed.
Any ideas? Thanks!
So you’re currently implementing an OR and want to implement an AND instead — is that it?
If so, then the
allsuggested in @Mark’s answer would work — or alternatively, and equivalently albeit at a lower level of abstraction:I’m not quite sure why you’re looping on
iteritemsand then ignoring the key you’re getting (appendingplayer.playerIDrather than theplayerIDkey directly).Anyway, another high-abstraction approach, assuming you don’t need the keys…:
This one doesn’t “short-circuit” but is otherwise equivalent to Mark’s. Fully equivalent, but quite concise:
If these code snippets don’t meet your needs, and you can clarify why exactly they don’t (ideally with an example or three!-), I’m sure they can be tweaked to satisfy said needs.