to_predicate

Contents

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 WithTag filter

  • type: Converted to an OfType filter

  • bool: True becomes Everything, False becomes Nothing

  • Ellipsis (…): Converted to Everything

  • None: Converted to Nothing

  • callable: Returned as-is

  • list or tuple: Converted to Any filter with elements as arguments

Returns:

A callable predicate function that takes (path, object) and returns bool.

Return type:

Callable[[Tuple[Key, ...], Any], bool]

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

WithTag

Filter for objects with specific tags

OfType

Filter for objects of specific types

Any

Logical OR combination of filters

Everything

Filter that matches all objects

Nothing

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