This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author vstinner
Recipients ag6502, alex, benjamin.peterson, brett.cannon, eric.araujo, ezio.melotti, flying sheep, kermit666, serhiy.storchaka, vstinner, xiang.zhang
Date 2016-03-08.12:36:32
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1457440593.34.0.483559243625.issue18156@psf.upfronthosting.co.za>
In-reply-to
Content
> 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.
History
Date User Action Args
2016-03-08 12:36:33vstinnersetrecipients: + vstinner, brett.cannon, ag6502, benjamin.peterson, ezio.melotti, eric.araujo, alex, flying sheep, serhiy.storchaka, kermit666, xiang.zhang
2016-03-08 12:36:33vstinnersetmessageid: <1457440593.34.0.483559243625.issue18156@psf.upfronthosting.co.za>
2016-03-08 12:36:33vstinnerlinkissue18156 messages
2016-03-08 12:36:32vstinnercreate