I have a Python 3 program which calls a C function. The C function returns an integer: 0 upon success, or the appropriate errno upon failure. Upon failure, the Python code could simply raise OSError. But I'd rather it raise the appropriate subclass of OSError.
For example, if the Python program gets the return code of 2, it should raise FileNotFoundError, a subclass of OSError. I can already find the correct subclass by doing the following three steps. Obviously, performance is not an issue because I need to do these steps only once per version of Python 3 for all values of errno, and cache the results.
- Find all the subclasses of
OSError. This is easy using__subclass__, recursively if necessary. - Map all the
errnovalues to names. For example, iferrnois 2, that should map toENOENT. This is done by parsing the appropriate C include file. On FreeBSD, for example, that file would be/usr/include/errno.h. - Map
errnonames toOSErrorsubclasses. This can be done by parsing the HTML code in, for example, http://docs.python.org/release/3.8.2/library/exceptions.html
But step 3 is really, really hokey. Is there a way I can do that step without parsing the documentation? Is there something I can inspect somehow in the Python that's sitting on my local host?