I would like to use the C implementation of a class method (created from Cython ), if present, or use its Python equivalent if the C extension is missing. I tried this first:
class A(object):
try:
import c_ext
method = c_ext.optimized_method
except ImportError:
def method(self):
return "foo"
Where optimized_method is a function defined in the Cython module :
def optimized_method(self):
return "fasterfoo"
But this does not work:
>>> A().method()
exceptions.TypeError: optimized_method() takes exactly one argument (0 given)
The only way I found this work:
class A(object):
def method(self):
try:
import c_ext
return c_ext.optimized_method(self)
except ImportError:
pass
return "foo"
But checking for the presence of a module with every function call seems rather suboptimal ... Why doesn't my first approach work?
[edit]: added Cython module contents
source
share