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

jmp jeanmichel at sequans.com
Mon Mar 7 05:50:05 EST 2016


On 03/07/2016 09:46 AM, 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.
>

Hi,

It is strange to morph an AttributeError in an HTTPError, anyway, you 
could write

try:
      fields = [getattr(Product, field) for field in fields.split(',')]
except AttributeError as e:
      raise HTTPError(str(e))

Or if you really need to write some custom message, you could parse the 
attribute error message for the attribute name.


# I've not tested this code !!
import re
try:
      fields = [getattr(Product, field) for field in fields.split(',')]
except AttributeError as e:
      # e.message should look like "class Foo has no attribute 'a'"
      attr = re.search(r"'(\w+)'", e.message).group(1)
      raise HTTPError('Custom message for the attribute %s' % attr)


Tbh I don't like it but it could do the job until someone raises you an 
attribute error with a different string pattern.

jm




More information about the Python-list mailing list