3.8.1. sciexp2.common.filter.Filter

Methods

match(source)

Check if the given source matches this filter.

validate(allowed)

Validate that variables in the filter are present in the given set.

class Filter(expression=None)

Bases: object

Boolean expression to check against a dict-like object.

The filter contains an arbitrary Python expression, where every variable will be taken from the dict we are matching the filter against.

Parameters:
expressionFilter or dict or str, optional

Expression to use in the filter.

Raises:
SyntaxError

The expression is not valid.

Notes

If expression is a dict-like object, it will define an expression that exactly matches its items.

Every filter will have the following global names defined:

re_match(var, str)

Check if var matches the regular expression str.

Examples

Filters can be easily composed together:

>>> f1 = Filter("a < 3")
>>> f2 = Filter("b == 4")
>>> and_filters(f1, f2)
Filter("(a < 3) and (b == 4)")
>>> or_filters(f1, f2)
Filter("(a < 3) or (b == 4)")

Filter objects can be later matched against dict-like objects:

>>> f = Filter("a < 3 and b == 4")
>>> f.match(dict(a=2, b=4))
True
>>> f.match(dict(a=3, b=4))
False

Using a dict as an expression is equivalent to building a perfect match for the dict’s items:

>>> Filter({"VAR1": 1, "VAR2": 2})
Filter("VAR1 == 1 and VAR2 == 2")
validate(allowed)

Validate that variables in the filter are present in the given set.

Parameters:
allowedset of variable names

Set of variable names to allow on the filter.

Raises:
NameError

Filter contains a variable name not present in allowed.

match(source)

Check if the given source matches this filter.

Parameters:
sourcedict-like

Dictionary to match this filter against.

Returns:
boolWhether the match is positive or not.
Raises:
NameError

Filter contains a variable name not present in source.

See also

validate