Skip to content
This repository has been archived by the owner on Apr 7, 2022. It is now read-only.

[1LP][WIPTEST] Add match_items() and first() #8018

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions cfme/modeling/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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. '''
Copy link
Member

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

Copy link
Member

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)

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. '''
Copy link
Member

Choose a reason for hiding this comment

The 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.

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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 singletone or only or something like that.

What do you think @mshriver

return next(iter(items))