Best python property decorator

I have inherited some python code that contains a rather cryptic decorator. This decorator sets properties in classes throughout the project. The problem is that I tracked my debugging problems with this decorator. This seems to scare all the debuggers I tried and try to speed up the code with psyco breaks everthing. (It seems psyco and this decorator do not play well). I think it would be better 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 this:

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

Errors that, as I understand it, are related to sys.settrace problems. (Perhaps this is an abuse of the assignment?)

My question is: is the same decorator available without sys.settrace. If not, I have serious rewrites.

+3
2

? . , , sys.settrace. ( sys.settrace, - - , - - .) , :

def Property(f):  
    fget, fset, fdel = f()
    fdoc = f.__doc__
    return property(fget, fset, fdel, fdoc)

class Foo(object):
    @Property
    def myprop():
        "Property docstring"
        def fget(self):  
            return 'fget' 
        def fset(self, x):
            pass
        def fdel(self):
            pass
        return fget, fset, fdel

Python 2.6 :

def Property(cls):
    fget = cls.__dict__.get('fget')
    fset = cls.__dict__.get('fset')
    fdel = cls.__dict__.get('fdel')
    fdoc = cls.__doc__
    return property(fget, fset, fdel, fdoc)

:

class Foo(object):
    @Property
    class myprop(object):
        "Property docstring"
        def fget(self):
            return 'fget'
        def fset(self, x):
            pass
        def fdel(self):
            pass

Python 2.6 :

class Foo(object):
    @property
    def myprop(self):
        "Property docstring"
        return 'fget'
    @myprop.setter
    def myprop(self, x):
            pass
    @myprop.deleter
    def myprop(self):
            pass
+8

, ; , settrace , , ...

, , , -: - (.

, , , , , sys.gettrace, , , .

+2

Source: https://habr.com/ru/post/1740521/


All Articles