"""Collection utilities for Haive Core - GetterMixin.This module includes powerful retrieval and filtering utilitiesfor collection classes."""fromcollections.abcimportCallablefromtypingimportAny,Generic,TypeVarT=TypeVar("T")
[docs]classGetterMixin(Generic[T]):"""A mixin providing rich lookup and filtering capabilities for collections. This mixin can be added to any collection class that implements _get_items() to provide powerful querying capabilities. """def_get_items(self)->list[T]:"""Get all items from the collection. Must be implemented by subclasses. """raiseNotImplementedError("Subclasses must implement _get_items()")
[docs]defget_by_attr(self,attr_name:str,value:Any,default:T|None=None)->T|None:"""Get first item where attribute equals value. Args: attr_name: Attribute name to check value: Value to match default: Default value if not found Returns: First matching item or default """foriteminself._get_items():ifself._has_attr_value(item,attr_name,value):returnitemreturndefault
[docs]defget_all_by_attr(self,attr_name:str,value:Any)->list[T]:"""Get all items where attribute equals value. Args: attr_name: Attribute name to check value: Value to match Returns: List of matching items """return[itemforiteminself._get_items()ifself._has_attr_value(item,attr_name,value)]
[docs]deffilter(self,**kwargs)->list[T]:"""Filter items by multiple attribute criteria. Args: **kwargs: Field name and value pairs to match Returns: List of matching items """results=[]foriteminself._get_items():match=Trueforattr,valueinkwargs.items():ifnotself._has_attr_value(item,attr,value):match=Falsebreakifmatch:results.append(item)returnresults
[docs]deffind(self,predicate:Callable[[T],bool])->T|None:"""Find first item matching a custom predicate function. Args: predicate: Function that takes item and returns boolean Returns: First matching item or None """foriteminself._get_items():ifpredicate(item):returnitemreturnNone
[docs]deffind_all(self,predicate:Callable[[T],bool])->list[T]:"""Find all items matching a custom predicate function. Args: predicate: Function that takes item and returns boolean Returns: List of matching items """return[itemforiteminself._get_items()ifpredicate(item)]
[docs]defget_by_type(self,type_cls:type)->list[T]:"""Get all items of specified type. Args: type_cls: Type to match Returns: List of matching items """return[itemforiteminself._get_items()ifisinstance(item,type_cls)]
[docs]deffield_values(self,field_name:str)->list[Any]:"""Get all values for a specific field across items. Args: field_name: Field name to collect Returns: List of field values """results=[]foriteminself._get_items():ifisinstance(item,dict)andfield_nameinitem:results.append(item[field_name])elifhasattr(item,field_name):value=getattr(item,field_name)results.append(value)else:results.append(None)returnresults
[docs]deffirst(self,**kwargs)->T|None:"""Get first item matching criteria. Args: **kwargs: Field name and value pairs to match Returns: First matching item or None """results=self.filter(**kwargs)returnresults[0]ifresultselseNone
def_has_attr_value(self,item:Any,attr:str,value:Any)->bool:"""Check if item has attribute with specified value. Args: item: Item to check attr: Attribute name value: Value to match Returns: True if attribute matches value """ifisinstance(item,dict):returnattrinitemanditem[attr]==valuereturnhasattr(item,attr)andgetattr(item,attr)==value