Using __getattr__ and properties in the same class is dangerous, because it can lead to errors that are very difficult to debug.
If the getter of a property throws AttributeError, then the AttributeError is silently caught, and __getattr__ is called. Usually, this causes __getattr__ to fail with an exception, but if you are extremely unlucky, it doesn't, and you won't even be able to easily trace the problem back to __getattr__.
Unless your property getter is trivial, you can never be 100% sure it won't throw AttributeError. The exception may be thrown several levels deep.
Here is what you could do:
- Avoid using properties and
__getattr__ in the same class.
- Add a
try ... except block to all property getters that are not trivial
- Keep property getters simple, so you know they won't throw
AttributeError
- Write your own version of the
@property decorator, which catches AttributeError and re-throws it as RuntimeError.
See also http://blog.devork.be/2011/06/using-getattr-and-property_17.html
EDIT: In case anyone is considering solution 4 (which I don't recommend), it can be done like this:
def property_(f):
def getter(*args, **kwargs):
try:
return f(*args, **kwargs)
except AttributeError as e:
raise RuntimeError, "Wrapped AttributeError: " + str(e), sys.exc_info()[2]
return property(getter)
Then use @property_ instead of @property in classes that override __getattr__.
AttributeErrorcan be raised in__get__(which is what you are effectively doing here) but doesn't explain what effect that has. It should probably say thatAttributeErrorsignals to python that it should behave as if the attribute has not been found (so that__getattr__is tried as a backup, as usual) - if that isn't the behaviour you want, then you should raise something else. - James