to_predicate#
- class brainstate.util.to_predicate(the_filter)[source]#
Convert a Filter to a predicate function.
This function takes various types of filters and converts them into corresponding predicate functions that can be used for filtering objects in nested structures.
- Parameters:
the_filter (
type|str|Callable[[Tuple[Key,...],Any],bool] |bool|Any|None|Tuple[type|str|Callable[[Tuple[Key,...],Any],bool] |bool|Any|None|Tuple[Filter,...] |List[Filter],...] |List[type|str|Callable[[Tuple[Key,...],Any],bool] |bool|Any|None|Tuple[Filter,...] |List[Filter]]) –The filter to be converted. Can be of various types:
str: Converted to a
WithTagfiltertype: Converted to an
OfTypefilterbool:
TruebecomesEverything,FalsebecomesNothingEllipsis (…): Converted to
EverythingNone: Converted to
Nothingcallable: Returned as-is
list or tuple: Converted to
Anyfilter with elements as arguments
- Returns:
A callable predicate function that takes (path, object) and returns bool.
- Return type:
- Raises:
TypeError – If the input filter is of an invalid type.
Examples
>>> from brainstate.util.filter import to_predicate >>> >>> # Convert string to WithTag filter >>> pred = to_predicate('trainable') >>> pred([], {'tag': 'trainable'}) True >>> >>> # Convert type to OfType filter >>> import numpy as np >>> pred = to_predicate(np.ndarray) >>> pred([], np.array([1, 2, 3])) True >>> >>> # Convert bool to Everything/Nothing >>> pred_all = to_predicate(True) >>> pred_all([], 'anything') True >>> pred_none = to_predicate(False) >>> pred_none([], 'anything') False >>> >>> # Convert list to Any filter >>> pred = to_predicate(['tag1', 'tag2']) >>> # This will match objects with either 'tag1' or 'tag2'
See also
WithTagFilter for objects with specific tags
OfTypeFilter for objects of specific types
AnyLogical OR combination of filters
EverythingFilter that matches all objects
NothingFilter that matches no objects
Notes
This function is the main entry point for creating predicate functions from various filter specifications. It provides a flexible way to define filtering criteria without explicitly instantiating filter classes.