Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: pass "not" as a lambda function [duplicate]

Tags:

python

lambda

I need to pass a function as a parameter that works as the boolean "not". I tried something like this but it didn't work because not isn't a function.

theFunction(callback=not) # Doesn't work :(

I need to do the following, but I wonder if there exists any predefined function that does this simple job, so that I don't have to redefine it like this:

theFunction(callback=lambda b: not b, anotherCallback=lambda b: not b)

Note: I can't change the fact that I have to pass a function like this because it's an API call.

like image 855
germanfr Avatar asked Feb 04 '18 18:02

germanfr


2 Answers

Yes, there is the operator module: https://docs.python.org/3.6/library/operator.html

import operator
theFunction(callback=operator.not_)
like image 127
quamrana Avatar answered Nov 04 '22 03:11

quamrana


not is not a function, but a keyword. So that means you can not pass a reference. There are good reasons, since it allows Python to "short circuit" certain expressions.

You can however use the not_ (with underscore) of the operator package:

from operator import not_

theFunction(callback=not_, anotherCallback=not_)
like image 24
Willem Van Onsem Avatar answered Nov 04 '22 04:11

Willem Van Onsem