Python - Determine if an exception was raised in a function

553 views Asked by At

I'm currently writing an extension to another Python library that I have no control over. The library has functions like this:

def xyz():
    try:
        sources = []
        ...
        #code that may add values to sources and may also throw an exception
        ...
        return sources
    except:
        return sources

If an empty list is returned, I want to somehow figure out if that is the case because an exception was thrown (before values could be added to sources), or because simply no values were added to sources (without throwing an exception).

Any ideas? Again, I don't have control over the function, so I can't change the return value or add the try->except outside the function.

1

There are 1 answers

0
bruno desthuilliers On

You can always try to monkeypatch the lib's function with a sane implementation instead:

import insanelib

def myxyz():
    sources = []
    ...
    #code that may add values to sources and may also throw an exception
    ...
    return sources


insanelib.xyz = myxyz

Or you can submit a patch to the lib's author so he at least provide an option to not ignore exceptions.