-
Notifications
You must be signed in to change notification settings - Fork 165
[1LP][WIPTEST] Add match_items() and first() #8018
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -190,3 +190,18 @@ def parent_of_type(obj, klass): | |
for x in _walk_to_obj_root(obj): | ||
if isinstance(x, klass): | ||
return x | ||
|
||
|
||
def match_items(items, filter): | ||
''' Return only items matching filter dict. ''' | ||
for item in items: | ||
for attr_name, val in filter.items(): | ||
if getattr(item, attr_name) != val: | ||
break | ||
else: | ||
yield item | ||
|
||
|
||
def first(items): | ||
''' Return the first item in the iterable. ''' | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this should definitely be a BaseCollection method, if its included at all. I'm hesitant to include it because its a single line wrapper that doesn't handle StopIteration to return None, or anything 'special' that would make it valuable beyond the caller just using next() or .pop() themselves. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This method is intended to be used when single item is expected to appear in some list or generator. So added value is that it handles both same way. We can discuss adding handling StopIteration and raising some other exception instead, if you think it something we should do. I've just realized I can be checking we got single and only value. So perhaps I should do that and rename this to What do you think @mshriver |
||
return next(iter(items)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
double quotes on these docblocks please
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider making this a BaseCollection classmethod instead of just this standalone method, for clarity during use and ability to call
self.match_items(self.all(), self.filters)