user3766476
user3766476

Reputation: 173

How to pass one function to another in python

I'm relatively new to python and I was wondering if it's possible to pass one function to another. I have some functions that basically do the same think like:

if(#some condition):
  #do something
else:
  #do something else

What I want to do is something like this:

def generic_func(self, x, y):
  if #somecondition:
   #do function x
  else:
   #do function y

def calls_generic_func(self, key, value):
  lambda x: self.list[-1].set(key,value)
  lambda y: self.d.set(key,value)
  self.generic_func(x,y)

Unfortunately this doesn't seem to work as when I call self.generic_fun(x,y) I get an error that says global name x is not defined. Any ideas?

Upvotes: 1

Views: 813

Answers (1)

falsetru
falsetru

Reputation: 369484

x in the following expression is a parameter, not a function (lambda).

lambda x: self.list[-1].set(key,value)

You need to assign the lambda expression to a variable and pass that.

function1 = lambda x: self.list[-1].set(key,value)
function2 = lambda y: self.d.set(key,value)
self.generic_func(function1, function2)

Or you can pass the lambda expression itself:

self.generic_func(lambda x: self.list[-1].set(key,value),
                  lambda y: self.d.set(key,value))

If you meant the functions do not take any parameter, remove them (x, y).

self.generic_func(lambda: self.list[-1].set(key,value),
                  lambda: self.d.set(key,value))

Upvotes: 2

Related Questions