is there a way of having an (yet unkown) function as an argument of a function in python:

def doSomething(<func>):
    #do something with func()

at a later stage, functions could be defined, eg:

def f1(x):
    return x*x

def f2(x):
    return x+1

and I could call now:

  • why the downvote ? – Newtopian Sep 13 '16 at 13:08
  • 2
    Yes. What happened when you tried? – RemcoGerlich Sep 13 '16 at 13:17
  • 2
    @Newtopian: lack of effort, and it should be on Stack Overflow. Scribbled a short answer anyway because why not, but it's not a good question for here. – RemcoGerlich Sep 13 '16 at 13:24
  • @RemcoGerlich thanks, indeed better for SO, it has in fact already been answered there :-) I was asking mostly for the OP`s sake, I find rude to downvote without (stating) reason, else how are we to correct innapropriate questions if we are not told what is wrong with them. – Newtopian Sep 13 '16 at 13:32

Functions are perfectly normal objects in Python, so the answer is yes.

def callFunctionTwice(func, arg):

def f(a):

callFunctionTwice(f, "hmm")  # Prints "hmm" twice
| improve this answer | |

Somebody answered better than I could at Stack Overflow, be sure to upvote his answer in addition (or instead of) my own if satisfactory.

but for completeness here are the takeaways :

  • define your own class and overload the call method
  • function object have it naturally, just call it to invoke the function
  • Lambda expressions can also get the desired effect
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.