After another terrible bug hunt, I am wondering the following: Is it possible to add some extra information to all exceptions, for example the name of an object. This would increase the readability of the errors a lot and make looking for bugs (or input errors) a lot quicker. This is especially the case if one has many objects which are from the same class and therefore share much code, but have different attributes. In this case it can be very useful if the error message also states the name of the object in the error.
A simplfied example: I am trying to simulate different types of facilities, a pig farm and a cow farm. These are the same class, but do have different attributes. In the simulation many facilities are made and if an exception is raised, it would be very helpful if the name of the object is added to the exception.
class facility():
def __init__(self, name):
self.name = name
self.animals = []
farms = []
farms.append(facility('cow_farm'))
farms.append(facility('pig_farm'))
print farms[0].stock
This would yield
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: facility instance has no attribute 'stock'
But I would like to add the name of the facility:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: facility instance has no attribute 'stock'
Name of object: cow_farm
I tried something like
def print_name(exception):
try:
print self.name
except AttributeError:
pass
raise exception
@print_name
Exception
But that doesn't work. Is it possible to do such a thing, or are there good reasons not to do this?