codefreak
codefreak

Reputation: 309

How to pass a function as argument to another function and use the value returned by that function in python?

I am trying to negate the value returned by one function.

Consider the code to be

def greater(a,b):
    return a>b

check = negate(greater)

assert check(8,9)

OR

def equal(a,b):
    return a==b

check = negate(equal)

assert check("python","java")

How should I define the NEGATE function???

Upvotes: 1

Views: 174

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121276

Use the not operator in a decorator:

from functools import wraps

def negate(func):
    @wraps(func)
    def wrapper(*args, **kw):
        return not func(*args, **kw)
    return wrapper

The above decorator returns a wrapper function that applies not to the return value of the wrapped function. The @functools.wraps() decorator in the above example is optional but makes sure the wrapper gains the docstring and other introspectable attributes from the original function, making it behave more closely like the wrapped function.

Demo:

>>> from functools import wraps
>>> def negate(func):
...     @wraps(func)
...     def wrapper(*args, **kw):
...         return not func(*args, **kw)
...     return wrapper
... 
>>> def greater(a,b):
...     return a>b
... 
>>> check = negate(greater)
>>> check(8, 9)
True

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

Use a function-style decorator:

def negate(func):
    def inner(*args, **kwargs):
        val = func(*args, **kwargs)
        return not val
    return inner

Demo:

>>> greater(10, 20)
False
>>> negate(greater)(10, 20)
True

To preserve things like docstring and other attributes of the function being passed to negate you can use functools.wraps.

from functools import wraps

def negate(func):
    @wraps(func)
    def inner(*args, **kwargs):
        val = func(*args, **kwargs)
        return not val
    return inner

Upvotes: 3

Linuxios
Linuxios

Reputation: 35783

Like this:

def negate(func):
  def result(*args):
    return not func(*args)
  return result

This is a function which creates a function which returns the result of invoking the original function and noting it's return value, and then returning that function.

Upvotes: 2

Related Questions