'How to customize general error messages of numpy?

I am writing a Vector and Matrix classes that use numpy in the backend in order to abstract some common methods and calculations (specifically, physics calculations, but it's irrelevant). I would like to intercept common errors that may occur with the usage of these classes in order to write more readable error messages and hide the usage of numpy.

For example, assume we have v = Vector([1, 2, 3]) defined. this code:

v["a"] = 5

generates the error:

IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

I would like something like:

TypeError: Vector can be indexed by int or slice (:), not str.

I am not sure why numpy raises IndexError here instead of TypeError but whatever. Another example is this code v[6] = 0 which generates:

IndexError: index 6 is out of bounds for axis 0 with size 3

I would prefer something like:

IndexError: index 6 is invalid for 3 dimensional vector

Another example: v[:2] = (4, 7, 12) which generates:

ValueError: could not broadcast input array from shape (3,) into shape (2,)

I'd prefer something like:

ValueError: Can't set 2d slice of vector with 3d data

There are probably more examples I didn't come up with yet, but I think this illustrates the point. I want to customize the error messages for these different operations and I can't figure out how.

I can catch the exceptions and raise new ones with proper messages, but the exception doesn't contain information about why it was raised. Was it because of a wrong type, out-of-bounds index, or wrong dimensions?

There is no error code or something like that. The best option I came up with is parsing the error messages to understand what happened, but this feels like cheating, a hard work, and it relies on numpy not changing the format of the error messages. Is there a more reliable and clean way to do so?



Solution 1:[1]

If you mean you want to access the stack trace by,

but the exception doesn't contain information about why it was raised.

you can use print(traceback.format_exc()) under the catch statement. Also you'll have to import import traceback.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saner Cakir