ActiveState Code

Recipe 502243: Property shortcut


This property shortcut doesn't restrict the property's attributes to get, set, del and doc. Besides these functions can have any name, not limited to fget, fset ... Note that the default doc is not the getter's one.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def propertx(fct):
    '''
        Decorator to simplify the use of property.
        Like @property for attrs who need more than a getter.
        For getter only property use @property.
    '''
    arg=[None, None, None, None]
    for i, f in enumerate(fct()):
        arg[i] = f
    if not arg[3] :
        arg[3]=fct.__doc__
    return property(*arg)

if __name__=='__main__':

    class example(object):
        def __init__(self):
            self._a=100
        @propertx
        def bar():
            # BAR doc
            def get(self):
                return self._a
            def set(self, val):
                self._a=val
            return get, set

    foo=example()
    print foo.bar
    foo.bar='egg'
    print foo.bar

Comments

  1. 1. At 12:04 p.m. on 21 feb 2007, Ian Bicking said:

    with classes... The recipe here might be of interest: http://svn.colorstudy.com/home/ianb/recipes/propertyclass.py

    It implements a property class that can be subclassed to create concrete properties.

  2. 2. At 12:05 p.m. on 6 may 2009, runsun pan said:

    This might be of interest:

    Easy Property Creation in Python http://code.activestate.com/recipes/576742/

    Only 7 lines of code, easy to understand, easy to use, easy to customize, save you a lot of typing

Sign in to comment