[PyQt] [SIP] Raise exception if Boolean return value is False

Phil Thompson phil at riverbankcomputing.com
Wed Jan 22 15:08:38 GMT 2014


On 22-01-2014 2:03 pm, Christian Aichinger wrote:
> Hi!
> I have several C functions that take an /Out/ parameter and return a
> bool to indicate success. SIP transforms this into a (bool, out_val)
> return on the Python side. Is there any way to generate a Python
> signature that returns the /Out/ value and raises an Exception if the
> boolean error return is False?
>
> What I have:
> SIP: bool MetersPerPixel(const MapPixelCoord &pos, double *mpp 
> /Out/);
>>>> success, mpp = MetersPerPixel(coord)
>
> What I want:
>>>> try: mpp = MetersPerPixel(coord)
>>>> except: # Handle the error case
>
> Currently I work around the issue by defining a new C++ function in
> %ModuleCode, which is then wrapped by SIP:
>
> %ModuleCode
> double MetersPerPixel(const MapPixelCoord &pos) {
>     double dbl;
>     if (!MetersPerPixel(pos, &dbl)) {
>         std::runtime_error("MetersPerPixel() failed.");
>     }
>     return dbl;
> }
> %End
> double MetersPerPixel(const MapPixelCoord &pos);

Better to use %MethodCode.

> However, I have a lot of these functions, and would rather not
> explicitly wrap all of them.

Sorry, no. An alternative would be to change the C++ library to raise a 
C++ exception.

Phil


More information about the PyQt mailing list