@property decorator doesn't raise exceptions

Peter Otten __peter__ at web.de
Mon Oct 27 03:47:54 EDT 2008


Rafe wrote:

> Can anyone explain why this is happening? 

When an attribute error is raised that is an indication that the requested
attribute doesn't exist, and __getattr__() must be called as a fallback.

> I can hack a work-around, 
> but even then I could use some tips on how to raise the 'real'
> exception so debugging isn't guesswork.

Look at the problem again, maybe you can find a solution without
__getattr__() and use only properties.

Otherwise you have to wrap your getter with something like

try:
    ...
except AttributeError:
    raise BuggyProperty, None, original_traceback


If you put that functionality into a decorator you get:

import sys

class BuggyProperty(Exception):
    pass

def safe_getter(get):
    def safe_get(self):
        try:
            return get(self)
        except AttributeError:
            t, e, tb = sys.exc_info()
            raise BuggyProperty("AttributeError in getter %s(); "
                            "giving original traceback"
                            % get.__name__), None, tb
    return property(safe_get)

class A(object):
    @safe_getter
    def attr(self):
        return self.m(3)
    
    def m(self, n):
        if n > 0:
            return self.m(n-1)
        raise AttributeError("it's a bug")

    def __getattr__(self, name):
        return "<%s>" % name

A().attr

Peter



More information about the Python-list mailing list