Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to pass a method (with parameters) to another method in python

Tags:

python

What's the best way to pass a method and a method parameter to another method?

Is there a better way to do the following?

def method1(name)
    return 'Hello ' + name

def method2(methodToCall, methodToCallParams, question):
    greetings = methodToCall(methodToCallParams)
    return greetings + ', ' + question

method2(method1, 'Sam', 'How are you?')
like image 458
Dan Avatar asked Dec 12 '25 20:12

Dan


1 Answers

If you want to package the invocation up in one hit, you can use the functools module:

from functools import partial

def some_function(param_one, param_two):
    print "Param One: %s" % param_one
    print "Param Two: %s" % param_two

def calling_function(target):
    target()

calling_function(partial(some_function, "foo", "bar"))

You can do tweakier things with functools.partial too, such as binding only some parameters, leaving you with a function with a new signature. It's overkill in a lot of cases to use it but it certainly has it's place.

like image 82
jkp Avatar answered Dec 15 '25 10:12

jkp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!