Dynamically using a class method defined in the Cython extension module

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

+3
source share
1

, ...

- , Cython , : , .

, :

class A(object):
    def method(self):
        return "foo"

try:
    import c_ext
    import types
    A.method = types.MethodType(c_ext.optimized_method, None, A)
except ImportError:
    pass
+4

Source: https://habr.com/ru/post/1706041/


All Articles