Add jarvis.utils.get
This commit is contained in:
parent
12870bba17
commit
e9532d1235
1 changed files with 18 additions and 0 deletions
|
@ -1,5 +1,6 @@
|
||||||
"""J.A.R.V.I.S. Utility Functions."""
|
"""J.A.R.V.I.S. Utility Functions."""
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from operator import attrgetter
|
||||||
from pkgutil import iter_modules
|
from pkgutil import iter_modules
|
||||||
from typing import Any, Callable, Iterable, Optional, TypeVar
|
from typing import Any, Callable, Iterable, Optional, TypeVar
|
||||||
|
|
||||||
|
@ -109,3 +110,20 @@ def find(predicate: Callable[[T], Any], seq: Iterable[T]) -> Optional[T]:
|
||||||
if predicate(element):
|
if predicate(element):
|
||||||
return element
|
return element
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get(iterable: Iterable[T], **attrs: Any) -> Optional[T]:
|
||||||
|
if len(attrs) == 1:
|
||||||
|
k, v = attrs.popitem()
|
||||||
|
pred = attrgetter(k.replace("__", "."))
|
||||||
|
for elem in iterable:
|
||||||
|
if pred(elem) == v:
|
||||||
|
return elem
|
||||||
|
return None
|
||||||
|
|
||||||
|
converted = [(attrgetter(attr.replace("__", ".")), value) for attr, value in attrs.items()]
|
||||||
|
|
||||||
|
for elem in iterable:
|
||||||
|
if all(pred(elem) == value for pred, value in converted):
|
||||||
|
return elem
|
||||||
|
return None
|
||||||
|
|
Loading…
Add table
Reference in a new issue