Message261355
> 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. |
|
Date |
User |
Action |
Args |
2016-03-08 12:36:33 | vstinner | set | recipients:
+ vstinner, brett.cannon, ag6502, benjamin.peterson, ezio.melotti, eric.araujo, alex, flying sheep, serhiy.storchaka, kermit666, xiang.zhang |
2016-03-08 12:36:33 | vstinner | set | messageid: <1457440593.34.0.483559243625.issue18156@psf.upfronthosting.co.za> |
2016-03-08 12:36:33 | vstinner | link | issue18156 messages |
2016-03-08 12:36:32 | vstinner | create | |
|