[Python-ideas] the error that raises an AttributeError should be passed to __getattr__

Steven D'Aprano steve at pearwood.info
Mon Jun 19 22:26:44 EDT 2017


On Tue, Jun 20, 2017 at 11:31:34AM +1000, Chris Angelico wrote:

> Why not just write cross-version-compatible code as
> 
> def __getattr__(self, name, error=None):
> 
> ? Is there something special about getattr?

You've still got to write it in the first place. That's a pain, 
especially since (1) it doesn't do you any good before 3.7 if not later, 
and (2) even if this error parameter is useful (which is yet to be 
established), it's a pretty specialised use. Most of the time, you 
already know the name that failed (its the one being looked up).

Perhaps a better approach is to prevent descriptors from leaking 
AttributeError in the first place? Change the protocol so that if 
descriptor.__get__ raises AttributeError, it is caught and re-raised as 
RuntimeError, similar to StopIteration and generators.

Or maybe we decide that it's actually a feature, not a problem, for an 
AttributeError inside self.attr.__get__ to look like self.attr is 
missing. I don't know.

(Also everything I said applies to __setattr__ and __delattr__ as well.)



-- 
Steve


More information about the Python-ideas mailing list