Python Function Pointer

Python function pointer

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

funcdict[myvar](parameter1, parameter2)

function pointers in python

Did you try it? What you wrote works exactly as written. Functions are first-class objects in Python.

Type of Python function pointer

I would use types.FunctionType to represent a function:

>>> import types
>>> types.FunctionType
<class 'function'>
>>>
>>> def func():
... pass
...
>>> type(func)
<class 'function'>
>>> isinstance(func, types.FunctionType)
True
>>>

You could also use a string literal such as 'function', but it looks like you want an actual type object.

Function pointer in cython extension type

You could use function pointer, but with a little bit more boilerplate code than in pure python, for example:

%%cython

# here all possible functions double->double
cdef double fun1(double x):
return 2*x

cdef double fun2(double x):
return x*x;
...

# class A wraps functions of type double->double
ctypedef double(*f_type)(double)

# boiler-plate code for obtaining the right functor
# uses NULL to signalize an error
cdef f_type functor_from_name(fun_name) except NULL:
if fun_name == "double":
return fun1
elif fun_name == "square":
return fun2
else:
raise Exception("unknown function name '{0}'".format(fun_name))

cdef class A:
cdef f_type fun

def __init__(self, fun_name ):
self.fun = functor_from_name(fun_name)

def apply(self, double x):
return self.fun(x)

I'm not aware of a possibility to get cdef-function pointer from the name of the function at run time and I don't think there is one out-of-the-box.

And now it works as advertised:

>>> doubler = A("double")
>>> double.apply(3.0)
6.0
>>> squarer = A("square")
>>> squarer.apply(3.0)
9.0
>>> dummy = A("unknown")
Exception: unknown function name 'unknown'

How to pass function pointers from class methods

If you want to inspect a class and print a name and
and function reference to each method which has an argspec
of two args see the code block below.

When inspecting the methods' argspec, if it has two args,
the first one in a class method is 'self', thus when calling,
it would only require one arg.

In the loop below: method[0] is the name and
method[1] is a method reference.

I haven't actually tried it but if you need to generate functions
from a class at runtime, I think this is down the correct path
to victory.

import inspect

class MyClass():
def m1(self, o):
return 'method1'
def m2(self, o):
return 'method2'

mc = MyClass()

for method in inspect.getmembers(mc):
if isinstance(method[1], type(mc.m1)):
if len(inspect.getfullargspec(method[1]).args) == 2:
print(f'mc.{method[0]}')
print(f' mc.{method[1]}')

>>> mc.m1
>>> mc.<bound method MyClass.m1 of <funcs_from_class.MyClass object at 0x11181e6d8>>
>>>mc.m2
>>> mc.<bound method MyClass.m2 of <funcs_from_class.MyClass object at 0x11181e6d8>>


Related Topics



Leave a reply



Submit