Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a method that receives parameters as a parameter of another function in Python

I know this is valid:

def printValue():
    print 'This is the printValue() method'

def callPrintValue(methodName):
    methodName()
    print 'This is the callPrintValue() method'

but is there a way to pass a method that receives parameters as a parameter of another function?

Doing this is not possible:

def printValue(value):
    print 'This is the printValue() method. The value is %s'%(value)

def callPrintValue(methodName):
    methodName()
    print 'This is the callPrintValue() method'

This is the stack trace i get:

This is the printValue() method. The value is dsdsd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in callPrintValue
TypeError: 'NoneType' object is not callable
like image 603
Lucas Avatar asked Nov 19 '25 01:11

Lucas


1 Answers

Some people find lambda ugly, but it is a useful tool in cases like this. Rather than modifying the signature of callPrintValue(), you can use lambda to quickly define a new function that binds the arguments to printValue(). Whether you really want to do this depends on many factors, and it may be that adding an *args parameter as others have suggested is preferable. Still, this is an option worth considering. The following works with no modifications to your current code:

>>> callPrintValue(lambda: printValue('"Hello, I am a value"'))
This is the printValue() method. The value is "Hello, I am a value"
This is the callPrintValue() method
like image 169
senderle Avatar answered Nov 20 '25 16:11

senderle



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!