How to get which attribute causes the AttributeError except inspecting strings?

Xiang Zhang zhangyangyu0614 at gmail.com
Mon Mar 7 05:15:43 EST 2016


On Monday, March 7, 2016 at 5:49:48 PM UTC+8, Peter Otten wrote:
> ZhangXiang wrote:
> 
> > In python3, when I write code like this:
> > 
> > try:
> >     fields = [getattr(Product, field) for field in fields.split(',')]
> > except AttributeError as e:
> >     raise HTTPError(...)
> > 
> > I want to raise a new type of error giving a string telling the user which
> > attribute is not valid. But I don't see any method I can use to get the
> > attribute name except inspecting e.args[0].
> > 
> > Could anyone give me a hint? Maybe I miss something.
> > 
> > By the way, I don't quite want to change my code to a for-loop so I can
> > access the field variable in exception handling.
> 
> It seems that the name of the attribute is not made available. You have to 
> parse the error message or provide the name yourself:
> 
> >>> def mygetattr(object, name):
> ...     try:
> ...         return getattr(object, name)
> ...     except AttributeError as err:
> ...         err.name = name
> ...         raise
> ... 
> >>> class Product:
> ...     foo = 42
> ... 
> >>> fields = "foo,bar"
> >>> try:
> ...     fields = [mygetattr(Product, field) for field in fields.split(",")]
> ... except AttributeError as err:
> ...     print(err)
> ...     print("Missing attribute:", err.name)
> ... 
> type object 'Product' has no attribute 'bar'
> Missing attribute: bar
> 
> Raising a subclass instead of mutating and reraising the original 
> AttributeError is probably cleaner...

Yes. It is a way to achieving that. But is it reasonable to add an attribute to AttributeError so we can easily get the attribute name?



More information about the Python-list mailing list