Negation of a function (function)
Does python have a built-in operator or function that negates another function? More specifically: a function that takes another function fun
(which returns a boolean) and returns a function that is a negative copy fun
.
Simple creation:
def neg(fun):
def negfun(x):
return not fun(x)
return negfun
Usage example:
In [1]: fun = lambda x: x < 3
In [2]: filter(fun, range(8))
Out[2]: [0, 1, 2]
In [3]: filter(neg(fun), range(8))
Out[3]: [3, 4, 5, 6, 7]
Maybe this is a bad example, just imagine the filter function already exists somewhere else and you want to use it.
I'm just surprised that I couldn't find an easier way ... is there one?
source to share
What you want to do is create an not
operator withfun
Unfortunately python doesn't have any nice "composition", so you'll have to wrap it yourself:
def compose(f, g):
return lambda x: f(g(x))
With this, you can write:
import operator
def neg(func):
return compose(operator.not, fun)
With that said, I find it much easier to read either your code or just using a lambda:
neg_func = lambda x: not fun(x)
source to share