jhaiduce
jhaiduce

Reputation: 438

Discovering which argument caused an error with Python CFFI

I'm using the Python CFFI module to wrap functions that have multiple arguments of the same type. If I pass the wrong type to one of the arguments, CFFI gives an error identifying the actual type and the expected type, but not the variable name or position in the argument list.

For example, the following code takes two arguments of the same type, and passes the wrong type to one of those arguments:

import cffi

ffi=cffi.FFI()

ffi.cdef('double mult(double x, double y);')
lib=ffi.verify('double mult(double x, double y){return x*y;};')
result=lib.mult(2,'3')

(I know ffi.verify is deprecated; I don't use it in my production code but it results in a much simpler MWE)

The above code gives the following output:

Traceback (most recent call last):
  File "/Users/haiducek/Development/cffi_type_error/cffi_type_error.py", line 7, in <module>
    result=lib.mult(2,'3')
           ^^^^^^^^^^^^^^^
TypeError: must be real number, not str

Is there a way to get CFFI to tell me which argument of the called function was responsible for the TypeError?

Upvotes: 1

Views: 40

Answers (1)

Armin Rigo
Armin Rigo

Reputation: 12990

Is there a way to get CFFI to tell me which argument of the called function was responsible for the TypeError?

Not at the moment. The error just comes from the innermost logic "convert this Python object to the C type double". This could be fixed by catching any error we get when trying to convert the Nth argument and re-raising it with extra information that gives at least the N.

There would be multiple places to change because there are multiple ways CFFI functions are built and called (times two if you consider CPython versus PyPy). PR welcomes?

Upvotes: 2

Related Questions