'Python exception type object inheritance

I need to retrieve the name of the object in which an error has occured. The error is catched in a try exception statement. The error type as returned by err_type, value, traceback = sys.exc_info() looks like this:

In [1]: err_type
Out[2]: mainsite.models.PurchaseOrder.DoesNotExist 

I need to retrieve 'PurchaseOrder' as a string. The idea is to get the parent object and then use parent.__name__.However if I write err_type.__bases__ the result is:

In [3]: err_type.__bases__
Out[4]: (django.core.exceptions.ObjectDoesNotExist,) 

I don't know what is happening here, the Exception type is not a child of PurchaseOrder, but somehow it knows that the problem was in that object. How can I retrive "PurchaseOrder" from the Exception?

I am doing this in Django, but it seems to be a general python topic.



Solution 1:[1]

Here's two approaches.

You can already obtain a string:

names = str(err_type).split('.')

Perhaps you'd like to pick out your favorite component.


Alternatively, you may find that

value.__mro__

reveals what you were looking for. It will show all parents in a multiple inheritance (mixin) situation.


It's worth point out that a single catch Exception: may be a poor fit for you here. Consider using a more fine grained approach:

    try:
        result = query()

    catch mainsite.models.PurchaseOrder.DoesNotExist:
        handle_missing_purchase_order()

    catch mainsite.models.Approval.DoesNotExist:
        handle_missing_approval()

    catch Exception as e:
        handle_unknown_error(e)

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