Python Function Pointer
I have a function name stored in a variable like this: myvar = 'mypackage.mymodule.myfunction' and I now want to call myfunction like this myvar(parameter1, parameter2) What's th
Solution 1:
funcdict = {
'mypackage.mymodule.myfunction': mypackage.mymodule.myfunction,
....
}
funcdict[myvar](parameter1, parameter2)
Solution 2:
deff(a,b):
return a+b
xx = 'f'printeval('%s(%s,%s)'%(xx,2,3))
OUTPUT
5
Solution 3:
Easiest
eval(myvar)(parameter1, parameter2)
You don't have a function "pointer". You have a function "name".
While this works well, you will have a large number of folks telling you it's "insecure" or a "security risk".
Solution 4:
Why not store the function itself? myvar = mypackage.mymodule.myfunction
is much cleaner.
Solution 5:
modname, funcname = myvar.rsplit('.', 1)
getattr(sys.modules[modname], funcname)(parameter1, parameter2)
Post a Comment for "Python Function Pointer"