Python function pointer

Python function pointer

funcdict = {
  mypackage.mymodule.myfunction: mypackage.mymodule.myfunction,

funcdict[myvar](parameter1, parameter2)

Its much nicer to be able to just store the function itself, since theyre first-class objects in python.

import mypackage

myfunc = mypackage.mymodule.myfunction
myfunc(parameter1, parameter2)

But, if you have to import the package dynamically, then you can achieve this through:

mypackage = __import__(mypackage)
mymodule = getattr(mypackage, mymodule)
myfunction = getattr(mymodule, myfunction)

myfunction(parameter1, parameter2)

Bear in mind however, that all of that work applies to whatever scope youre currently in. If you dont persist them somehow, you cant count on them staying around if you leave the local scope.

Python function pointer

def f(a,b):
    return a+b

xx = f
print eval(%s(%s,%s)%(xx,2,3))



Leave a Reply

Your email address will not be published. Required fields are marked *