[Python-ideas] Specificity in AttributeError

Masklinn masklinn at masklinn.net
Sat Apr 27 15:05:50 CEST 2013


I don't know if it ties into this proposal or not, but I've had a pair
of issues with attribute resolution in the past and more specifically
with __getattr__:

1. __getattr__ is not implemented on object, thus implementing __getattr__
   in an inheritance hierarchy (where an other object in an MRO may also
   have implemented __getattr__) requires boilerplate along the lines of:

    sup = getattr(super(Cls, self), '__getattr__', None)
    if sup is not None:
        return sup(key)

2. __getattr__ *must raise* to signify a missing attribute as None will
   simply be returned. The issue here is twofold:

   * the exception message will often be nothing like the default one
   * the stack will be all wrong, as it will show "within" the __getattr__
     call, making it harder to discriminate between an expected attribute
     error and something unexpectedly blowing up within __getattr__

I was wondering if it wouldn't be possible to add __getattr__ to object,
which would return NotImplemented. And NotImplemented would be interpreted
by the attribute resolution process as "raise the normal AttributeError" as
if there had not been a __getattr__. This way, attribute errors from
__getattr__ not matching the provided name would look much more natural.

I also believe it is backwards compatible: current __getattr__
implementations which just raise & don't delegate to a super() will
behave exactly the same way, with the same issues.



More information about the Python-ideas mailing list