[issue18156] Add an 'attr' attribute to AttributeError

STINNER Victor report at bugs.python.org
Tue Mar 8 07:36:33 EST 2016


STINNER Victor added the comment:

> try:
>   cls.meth()
> except AttributeError as exc:
>   if exc.attr != 'meth':
>     raise

What if cls.__getattr__('meth') calls a completly unrelated function which also raises AttributeError(attr='meth') but on a different object? I would also expect an "obj" attribute, a reference to the object which doesn't have attribute.

But AttributeError can be raised manually without setting attr and/or obj attribute. So the best test would look to something like:

if exc.obj is cls and exc.attr is not None and exc.attr != 'meth':
    raise

The test is much more complex than expected :-/ Maybe it's simpler to split the code to first get the bounded method?

try:
   meth = cls.meth
except AttributeError:
   ...
meth()

Or check first if cls has the attribute 'meth' with hasattr(cls, 'meth')?

--

About attr/obj attribute not set, an alternative is to add a new BetterAttributeError(obj, attr) exception which requires obj and attr to be set, it inherits from AttributeError.

class BetterAttributeError(AttributeError):
   def __init__(self, obj, attr):
       super().__init__('%r has no attribute %r' % (obj, attr)
       self.obj = obj
       self.attr = attr

It would allow a smoother transition from "legacy" AttributeError to the new BetterAttributeError.

The major issue with keeping a strong reference to the object is that Python 3 introduced Exception.__traceback__ which can create a reference cycle if an exception is stored in a local variable somewhere in the traceback. It's a major pain point in asyncio. In asyncio, the problem is more likely since exceptions are stored in Future objects to be used later.

----------
nosy: +haypo

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue18156>
_______________________________________


More information about the Python-bugs-list mailing list