[Python-ideas] Two small functional-style-related improvements

Jan Kaliszewski zuo at chopin.edu.pl
Sun Mar 27 15:05:36 CEST 2011

Steven D'Aprano dixit (2011-03-27, 14:41):

> Jan Kaliszewski wrote:
> >* operator.is_none -- equivalent to (lambda x: x is None))
> >* operator.is_not_none -- equivalent tolambda x: x is not None))
> >
> >...making using 'is None'/'is not None' tests with any(), all(),
> >filter(), itertools.takewhile/dropwhile() more convenient and readable
> >(possibly also optimised for speed).
> How is
> import operator
> any(map(operator.is_none, iterable))
> more convenient and readable than:
> any(x is None for x in iterable)

It isn't indeed -- but I'd prefer e.g.:

    filter(is_not_none, iterable)

...rather than:

    filter(None, (x is not None for x in iterable))

(not saying about more complex cases, when additional inner for-loop
makes the expression much less readable).

And --what is maybe more important-- such functions as
itertools.dropwhile, itertools.takewhile, itertools.groupby (together
with .sort/sorted) do not have their generator expression counterparts
(at least resonably simple ones). Ane then, if we wish to stay in the
functional-style we must use ugly lambdas/partial for now.

> >2. ...to add:
> >
> >* operator.anti_caller (or e.g. functools.negator?) -- equivalent to:
> >
> >def anti_caller(func):
> >    def call_and_negate(*args, **kwargs):
> >        return not func(*args, **kwargs)
> >    return call_and_negate
> This seems to be a decorator, so I don't believe it belongs in the
> operator module.

Yes, maybe rather: functools.negated

> Either way, I don't see the point to it.
> What is your use-case for this function?

I'd would like to be able to do:

    assert any(dropwhile(negated(str.isalnum),
                         takewhile(negated(str.isspace), my_names)))

...instead of:

    assert any(dropwhile(lambda name: not name.isalnum(),
                         takewhile(lambda name: not name.isspace(),


More information about the Python-ideas mailing list