I am working on a Python project that uses swig to connect the main Python code to a C++ module. I recently added a new function to the C++ library, but in functions with the @numpy.vectorize
decorator, the new function triggers a TypeError
when one of the inputs is a NumPy array of type numpy.float64
as one of the inputs. I have observed that vectorized functions automatically call the first entry in such an array input as numpy.float64
(which Swig cannot, by default, cast to C++ double
) before running every entry in the array as a Python float
.
@np.vectorize
def test(mu):
print(mu,type(mu))
test(np.array([6.2, 67.3]))
6.2 <class 'numpy.float64'>
6.2 <class 'float'>
67.3 <class 'float'>
However, older C++ functions called from vectorized functions do not cause this problem, even in a function that also calls one of the new C++ functions and looks somewhat like:
@np.vectorize
def eps(t,mu):
if t > 0:
return cpplib.old_func(mu)
else:
return cpplib.new_func(mu)
Both C++ functions accept a double
input and return a double
output. I do not observe any obvious differences in the old and new C++ functions, their instances in the directory's .h
file, the project directory's wrap.i
, or the Swig-generated wrapper code for the C++ module.
NumPy's online documentation for numpy.i recommends copying pyfragments.swg
from the NumPy source code into the project directory, but I didn't need this previously and doing so caused compilation errors.
I encountered the same problem in an earlier stage of the project, but my colleague couldn't reproduce it on his system, and eventually the problem went away for me as well. All I know is that fixing syntax errors in the C++ library did not make the problem go away.