Inverting a conditional function
On 6/9/2018 5:54 AM, Steven D'Aprano wrote:
> I frequently have a function which tests some condition, returning True
> or False, and want a function which reverses the condition.
> If all I wanted was the result of calling the function, I could say
> not condition(x)
> and be done with it, but I want a new function. I've been doing this:
> lambda arg: not condition(arg)
def not_condition(arg): return not condition(arg)
> which is okay, but its a bit long and adds the cost of an extra function
> call. Is there a better way?
If you have access to source, replace each 'return e' with 'return not
e' or perhaps 'return not (e)'. Don't replace 'not not e' unless you
know 'e' evaluates to False or True.
Otherwise, disassemble the function, replace code for return with code
for invert, return. Assemble new function.
Terry Jan Reedy