Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature request (function request) #8

Closed
floer32 opened this issue Dec 22, 2013 · 4 comments
Closed

feature request (function request) #8

floer32 opened this issue Dec 22, 2013 · 4 comments

Comments

@floer32
Copy link

floer32 commented Dec 22, 2013

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
Copy link
Owner

Suor commented Dec 23, 2013

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
Copy link
Owner

Suor commented Dec 23, 2013

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

@floer32
Copy link
Author

floer32 commented Dec 28, 2013

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

@floer32
Copy link
Author

floer32 commented Apr 17, 2014

closing

@floer32 floer32 closed this as completed Apr 17, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants