[Python-ideas] AtributeError inside __get__

Nick Coghlan ncoghlan at gmail.com
Fri Dec 30 09:55:32 EST 2016


On 26 December 2016 at 21:23, Zahari Dim <zaharid at gmail.com> wrote:

> > There are a lot of entirely valid properties that look something like
> this:
> >
> >
> >     @property
> >     def attr(self):
> >         try:
> >             return data_store[lookup_key]
> >         except KeyError:
> >             raise AttributeError("attr")
>
> But wouldn't something like this be implemented more commonly with
> __getattr__ instead (likely there is more than one such property in a
> real example)?  Even though __getattr__ has a similar problem (a bad
> AttributeError inside can cause many bugs), I'd agree it would
> probably be too difficult to change that without breaking a lot of
> code. For __get__, the errors are arguably more  confusing (e.g. when
> used with @property) and the legitimate use case, while existing,
> seems more infrequent to me: I did a github search and there was a
> small number of cases, but most were for code written in python 2
> anyway.


Aye, I agree this pattern is far more common in __getattr__ than it is in
descriptor __get__ implementations or in property getter implementations.

Rather than changing the descriptor protocol in general, I'd personally be
more amenable to the idea of *property* catching AttributeError from the
functions it calls and turning it into RuntimeError (after a suitable
deprecation period). That way folks that really wanted the old behaviour
could define their own descriptor that works the same way property does
today, whereas if the descriptor protocol itself were to change, there's
very little people could do to work around it if it wasn't what they wanted.

Exploring that possible approach a bit further:

- after a deprecation period, the "property" builtin would change to
convert any AttributeError raised by the methods it calls into RuntimeError
- the current "property" could be renamed "optionalproperty": the methods
may raise AttributeError to indicate the attribute isn't *really* present,
even though the property is defined at the class level
- the deprecation warning would indicate that the affected properties
should switch to using optionalproperty instead

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161231/3b696d43/attachment.html>


More information about the Python-ideas mailing list