A better python property decorator

Posted by leChuck on Stack Overflow See other posts from Stack Overflow or by leChuck
Published on 2010-04-09T20:17:49Z Indexed on 2010/04/09 20:23 UTC
Read the original article Hit count: 357

Filed under:
|
|
|

I've inherited some python code that contains a rather cryptic decorator. This decorator sets properties in classes all over the project. The problem is that this I have traced my debugging problems to this decorator. Seems it "fubars" all debuggers I've tried and trying to speed up the code with psyco breaks everthing. (Seems psyco and this decorator dont play nice). I think it would be best to change it.

def Property(function):
    """Allow readable properties"""
    keys = 'fget', 'fset', 'fdel'
    func_locals = {'doc':function.__doc__}
    def probeFunc(frame, event, arg):
        if event == 'return':
            locals = frame.f_locals
            func_locals.update(dict((k,locals.get(k)) for k in keys))
            sys.settrace(None)
        return probeFunc
    sys.settrace(probeFunc)
    function()
    return property(**func_locals)

Used like so:

class A(object):
    @Property
    def prop():
        def fget(self):
            return self.__prop
        def fset(self, value):
            self.__prop = value
    ... ect

The errors I get say the problems are because of sys.settrace. (Perhaps this is abuse of settrace ?)

My question: Is the same decorator achievable without sys.settrace. If not I'm in for some heavy rewrites.

© Stack Overflow or respective owner

Related posts about python

Related posts about decorator