skrub.Expr.skb.match#

Expr.skb.match(targets, default=NULL)[source]#

Select based on the value of an expression.

First, self is evaluated. Then, the result is compared to the keys in the mapping targets. If a key matches, the corresponding value is evaluated and the result is returned. If there is no match and default has been provided, default is evaluated and returned. If there is no match and no default a KeyError is raised.

Therefore, only one of the branches or the default is evaluated which is the main advantage compared to placing the selection inside a @skrub.deferred function.

Parameters:
targetsdict

A dictionary providing which result to select. The keys must be actual values, they cannot be expressions. The values can be expressions or any object.

defaultobject, optional

If provided, the match falls back to the default when none of the targets have matched.

Returns:
The value corresponding to the matching key or the default

See also

skrub.deferred

Wrap function calls in an expression Expr.

Examples

>>> import skrub
>>> a = skrub.var("a")
>>> mode = skrub.var("mode")
>>> @skrub.deferred
... def mul(value, factor):
...     result = value * factor
...     print(f"{value} * {factor} = {result}")
...     return result
>>> b = mode.skb.match(
...     {"one": mul(a, 1.0), "two": mul(a, 2.0), "three": mul(a, 3.0)},
...     default=mul(a, -1.0),
... )
>>> b.skb.eval({"a": 10.0, "mode": "two"})
10.0 * 2.0 = 20.0
20.0
>>> b.skb.eval({"a": 10.0, "mode": "three"})
10.0 * 3.0 = 30.0
30.0
>>> b.skb.eval({"a": 10.0, "mode": "twenty"})
10.0 * -1.0 = -10.0
-10.0

Note that only one of the multiplications gets evaluated.