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 <rep...@bugs.python.org>
<http://bugs.python.org/issue18156>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to