Python function pointer Python function pointer python python

Python function pointer


funcdict = {  'mypackage.mymodule.myfunction': mypackage.mymodule.myfunction,    ....}funcdict[myvar](parameter1, parameter2)


It's much nicer to be able to just store the function itself, since they're first-class objects in python.

import mypackagemyfunc = mypackage.mymodule.myfunctionmyfunc(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 you're currently in. If you don't persist them somehow, you can't count on them staying around if you leave the local scope.


def f(a,b):    return a+bxx = 'f'print eval('%s(%s,%s)'%(xx,2,3))

OUTPUT

 5