[Python-ideas] AtributeError inside __get__

Zahari Dim zaharid at gmail.com
Mon Dec 26 06:23:18 EST 2016


> 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. Here a couple of valid ones:

https://github.com/dimavitvickiy/server/blob/a9a6ea2a155b56b84d20a199b5948418d0dbf169/orm/decorators.py
https://github.com/dropbox/pyston/blob/75562e57a8ec2f6f7bd0cf52012d49c0dc3d2155/test/tests/static_class_methods.py

Cheers,

Zahari
>
> This is one of the many cases where IDEs with some form of static structural
> checking really do make development easier - the "self.nonexisting" would be
> flagged as non-existent directly in the editor, even before you attempted to
> run the code.

In my particular case, the class had a __getattr__ that generated
properties dynamically. Therefore an IDE was unlikely to be helpful.

>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list