collections - Various collection types¶
Overview¶
This module provides data structures that behave much like builtin list and dict types,
but with direct support of operations that can use structured data stored in container, and
which would normally require utilization of operator, functools or other means.
All containers provide next operations:
filterandfilterfalsethat return generator that yields items for whichexpris evaluated as True (or False).findthat returns first item for whichexpris evaluated as True, or default.containsthat returns True if there is any item for whichexpris evaluated as True.occurrencethat returns number of items for whichexpris evaluated as True.allandanythat return True ifexpris evaluated as True for all or any list element(s).reportthat returns generator that yields data produced by expression(s) evaluated on list items.
Individual collection types provide additional operations like splitting and extracting based on expression etc.
Expressions used by these methods could be strings that contain Python expression referencing the collection item(s), or lambda functions.
Types for type hints & annotations¶
- firebird.base.collections.Item = typing.Any¶
Collection Item
- firebird.base.collections.TypeSpec¶
Collection Item type specification
- firebird.base.collections.ItemExpr¶
Collection Item sort expression
Collections¶
- class firebird.base.collections.BaseObjectCollection[source]¶
Bases:
objectBase class for collection of objects.
- all(expr: FilterExpr) bool[source]¶
Return True if
expris evaluated as True for all list elements.- Parameters:
expr (FilterExpr) – Bool expression, a callable accepting one parameter and returning bool or bool expression as string referencing list item as
item.- Return type:
Example
L.all(lambda x: x.name.startswith("ABC")) L.all('item.name.startswith("ABC")')
- any(expr: FilterExpr) bool[source]¶
Return True if
expris evaluated as True for any list element.- Parameters:
expr (FilterExpr) – Bool expression, a callable accepting one parameter and returnin bool or bool expression as string referencing list item as
item.- Return type:
Example
L.any(lambda x: x.name.startswith("ABC")) L.any('item.name.startswith("ABC")')
- contains(expr: FilterExpr = None) bool[source]¶
Returns True if there is any item for which
expris evaluated as True.- Parameters:
expr (FilterExpr) – Bool expression, a callable accepting one parameter and returning bool or bool expression as string referencing list item as
item.- Return type:
Example
if L.contains(lambda x: x.name.startswith("ABC")): ... if L.contains('item.name.startswith("ABC")'): ...
- filter(expr: FilterExpr) Generator[Item, None, None][source]¶
Returns generator that yields items for which
expris evaluated as True.- Parameters:
expr (FilterExpr) – Bool expression, a callable accepting one parameter and returning bool or bool expression as string referencing list item as
item.- Return type:
Generator[Item, None, None]
Example
L.filter(lambda x: x.name.startswith("ABC")) L.filter('item.name.startswith("ABC")')
- filterfalse(expr: FilterExpr) Generator[Item, None, None][source]¶
Returns generator that yields items for which
expris evaluated as False.- Parameters:
expr (FilterExpr) – Bool expression, a callable accepting one parameter and returning bool or bool expression as string referencing list item as
item.- Return type:
Generator[Item, None, None]
Example
L.filterfalse(lambda x: x.name.startswith("ABC")) L.filterfalse('item.name.startswith("ABC")')
- find(expr: FilterExpr, default: Any = None) Item[source]¶
Returns first item for which
expris evaluated as True, or default.- Parameters:
expr (FilterExpr) – Bool expression, a callable accepting one parameter and returning bool or bool expression as string referencing list item as
item.default (Any) – Default value returned when Items is not found.
- Return type:
Item
Example
L.find(lambda x: x.name.startswith("ABC")) L.find('item.name.startswith("ABC")')
- occurrence(expr: FilterExpr) int[source]¶
Return number of items for which
expris evaluated as True.- Parameters:
expr (FilterExpr) – Bool expression, a callable accepting one parameter and returning bool or bool expression as string referencing list item as
item.- Return type:
Example
L.occurrence(lambda x: x.name.startswith("ABC")) L.occurrence('item.name.startswith("ABC")')
- report(*args) Generator[Any, None, None][source]¶
Returns generator that yields data produced by expression(s) evaluated on list items.
- Parameters:
args –
Parameter(s) could be one from:
A callable accepting one parameter and returning data for output
One or more expressions as string referencing item as
item.
- Return type:
Example
# generator of tuples with item.name and item.size L.report(lambda x: (x.name, x.size)) L.report('item.name','item.size') # generator of item names L.report(lambda x: x.name) L.report('item.name')
- class firebird.base.collections.DataList(items: Iterable = None, type_spec: TypeSpec = Sentinel('UNDEFINED'), key_expr: str = None, frozen: bool = False)[source]¶
Bases:
List[Any],BaseObjectCollectionList of data (objects) with additional functionality.
- __init__(items: Iterable = None, type_spec: TypeSpec = Sentinel('UNDEFINED'), key_expr: str = None, frozen: bool = False)[source]¶
- Parameters:
items (Iterable) – Sequence to initialize the collection.
type_spec (TypeSpec) – Reject instances that are not instances of specified types.
key_expr (str) – Key expression. Must contain item referrence as
item, for exampleitem.attribute_name. If all classes specified intype_specare descendants ofDistinct, the default value isitem.get_key(), otherwise the default isNone.frozen (bool) – Create frozen list.
- Raises:
ValueError – When initialization sequence contains invalid instance.
- append(item: Item) None[source]¶
Add an item to the end of the list.
- Raises:
TypeError – When item is not an instance of allowed class, or list is frozen
- Parameters:
item (Item) –
- Return type:
None
- clear() None[source]¶
Remove all items from the list.
- Raises:
TypeError – When list is frozen.
- Return type:
None
- extend(iterable: Iterable) None[source]¶
Extend the list by appending all the items in the given iterable.
- extract(expr: FilterExpr, copy: bool = False) DataList[source]¶
Move/copy items for which
expris evaluated as True into newDataList.- Parameters:
expr (FilterExpr) – A callable accepting one parameter or expression as string referencing list item as
item.copy (bool) – When True, items are not removed from source DataList.
- Raises:
- Return type:
Example
L.extract(lambda x: x.name.startswith("ABC")) L.extract('item.name.startswith("ABC")')
- freeze() None[source]¶
Set list to immutable (frozen) state.
Freezing list makes internal map from
key_exprto item index that significantly speeds up retrieval by key using theget()method.It’s not possible to
add,deleteorchangeitems in frozen list, butsortis allowed.- Return type:
None
- get(key: Any, default: Any = None) Item[source]¶
Returns item with given key using default key expression. Returns
defaultvalue if item is not found.Uses very fast method to look up value of default key expression in
frozenlist, otherwise it uses slower list traversal.- Parameters:
- Raises:
Error – If key expression is not defined.
- Return type:
Item
Example
# Search using default key expression (fast for frozen list) L.get('ITEM_NAME')
- remove(item: Item) None[source]¶
Remove first occurrence of item.
- Raises:
ValueError – If the value is not present, or list is frozen
- Parameters:
item (Item) –
- Return type:
None
- sort(attrs: List = None, expr: ItemExpr = None, reverse: bool = False) None[source]¶
Sort items in-place, optionaly using attribute values as key or key expression.
- Parameters:
attrs (List) – List of attribute names.
expr (ItemExpr) – Key expression, a callable accepting one parameter or expression as string referencing list item as
item.Important – Only one parameter (
attrsorexpr) could be specified. If none is present then uses default list sorting rule.reverse (bool) –
- Return type:
None
Example
L.sort(attrs=['name','degree']) # Sort by item.name, item.degree L.sort(expr=lambda x: x.name.upper()) # Sort by upper item.name L.sort(expr='item.name.upper()') # Sort by upper item.name
- split(expr: FilterExpr, frozen: bool = False) Tuple[DataList, DataList][source]¶
Return two new
DataListinstances, first with items for whichexpris evaluated as True and second forexprevaluated as False.- Parameters:
expr (FilterExpr) – A callable accepting one parameter or expression as string referencing list item as
item.frozen (bool) – Create frozen lists.
- Return type:
Example
below, above = L.split(lambda x: x.size > 100) below, above = L.split('item.size > 100')
- property key_expr: Item¶
Key expression.
- class firebird.base.collections.Registry(data: Mapping | Sequence | Registry = None)[source]¶
Bases:
BaseObjectCollection,Mapping[Any,Distinct]Mapping container for
Distinctobjects.Any method that expects a
keyalso aceptsDistinctinstance.- To store items into registry with existence check, use:
R.store(item)
R.extend(items) or R.extend(item)
- To update items in registry (added if not present), use:
R[key] = item
R.update(items) or R.update(item)
- To check presence of item or key in registry, use:
key in R
- To retrieve items from registry, use:
R.get(key, default=None)
R[key]
R.pop(key, default=None)
R.popitem(last=True)
- To delete items from registry, use:
R.remove(item)
del R[key]
Whenever a
keyis required, you can use either aDistinctinstance, or any value that represens a key value for instances of stored type.- Parameters:
data (Union[Mapping, Sequence, Registry]) –
- pop(key: Any, default: Any = None) Distinct[source]¶
Remove specified
keyand return the correspondingDistinctobject. Ifkeyis not found, thedefaultis returned if given, otherwiseKeyErroris raised.
- popitem(last: bool = True) Distinct[source]¶
Returns and removes a
Distinctobject. The objects are returned in LIFO order iflastis true or FIFO order if false.
- remove(item: Distinct)[source]¶
Removes item from registry (same as: del R[item]).
- Parameters:
item (Distinct) –