Suor/funcy

feature request (function request)

Closed this issue · 4 comments

I love where. What about another similar function, that takes predicates instead of values? Not sure what to call it, but it behaves like this:

def filterwhere(mappings, **preds):
    """ Like `where` but instead of value equality checks, use predicate functions.

    .. doctest ::

        >>> mappings = [{'foo': 'a', 'bar': 16},
        ...  {'foo': 'b', 'bar': 32},
        ...  {'foo': 'd', 'bar': 128, '': ''},
        ...  {'foo': 'e', 'bar': 123, 'baz': 'quux'},
        ...  {'foo': 'c', 'bar': 6400},
        ...  {'foo': 'f', 'bar': float("inf")},]
        >>> x = filterwhere(mappings, bar=lambda bar: bar < 100)
        >>> assert x == [{'foo': 'a', 'bar': 16}, {'foo': 'b', 'bar': 32}]
        >>> y = filterwhere(
        ...     mappings, bar=lambda n: n % 2 != 0 and n < 1000)
        >>> assert y == [{'foo': 'e', 'bar': 123, 'baz': 'quux'}]

    :param mappings: A sequence of mappings, for example a list of dicts.
    :param preds: Any number of predicate functions. Each mapping must
        pass `pred(mapping[key_of_mapping])` for each keyword argument pair of
        `key_of_mapping=pred`.
    :return: A sequence of mappings.
    """
    match = lambda m: all(pred(m[k]) for k, pred in preds.items())
    return filter(match, mappings)
Suor commented

I like such little neat things too. However, there is good solution for such situation in python - list comprehensions. So, even where is a stretch. I try to limit funcy scope at some level which makes me resistant to adding new things like this.

So I won't add it, sorry. I will still leave this issue open in case it will attract more interest. Then I'll probably reconsider.

Suor commented

P.S. You might want to look at this library for terser anonymous functions syntax.

Yeah, that's true. List comprehensions do solve this very well. Thanks for pointing out whatever, too!

closing