I have the following structure in my code:
#test.pyx
cdef class BClass:
cdef str x
cdef set_args(self, x):
self.x = x
cdef func(self, x):
print "BClass" , self.x, "--", x
fit = BClass()
def my_func():
global fit
fit.set_args("hello")
fit.func("world")
#tester.py
import test
test.my_func()
I build pyx into a pyd without problem, but when I run tester.py I get the following error:
AttributeError: ‘test.BClass’ object has no attribute ‘set_args’
If I instantiate fit inside my_func all works as expected. Does this mean I can’t define a module level object and then reuse it in a function in the same module?
In my original code my_func is called repeatedly in a loop and instantiating a BClass has some overhead due to allocating some arrays, that’s why I want to instantiate fit outside my_func. Any thoughts how to do this?
Well, the solution is embarrassingly simple. Just declaring fit as
at a module level makes it work without any errors.
I still don’t understand why if fit is instantiated the Python way with
then I get this AttributeError and why if I instantiate it in the Python way inside my_func() it works without error???