[Python-Dev] The decorator(s) module
Duncan Booth
duncan.booth at suttoncourtenay.org.uk
Sat Feb 11 14:29:07 CET 2006
Georg Brandl <g.brandl at gmx.net> wrote in news:dsj0p7$tk3$1 at sea.gmane.org:
> Unfortunately, a @property decorator is impossible...
>
It all depends what you want (and whether you want the implementation to be
portable to other Python implementations). Here's one possible but not
exactly portable example:
from inspect import getouterframes, currentframe
import unittest
class property(property):
@classmethod
def get(cls, f):
locals = getouterframes(currentframe())[1][0].f_locals
prop = locals.get(f.__name__, property())
return cls(f, prop.fset, prop.fdel, prop.__doc__)
@classmethod
def set(cls, f):
locals = getouterframes(currentframe())[1][0].f_locals
prop = locals.get(f.__name__, property())
return cls(prop.fget, f, prop.fdel, prop.__doc__)
@classmethod
def delete(cls, f):
locals = getouterframes(currentframe())[1][0].f_locals
prop = locals.get(f.__name__, property())
return cls(prop.fget, prop.fset, f, prop.__doc__)
class PropTests(unittest.TestCase):
def test_setgetdel(self):
class C(object):
def __init__(self, colour):
self._colour = colour
@property.set
def colour(self, value):
self._colour = value
@property.get
def colour(self):
return self._colour
@property.delete
def colour(self):
self._colour = 'none'
inst = C('red')
self.assertEquals(inst.colour, 'red')
inst.colour = 'green'
self.assertEquals(inst._colour, 'green')
del inst.colour
self.assertEquals(inst._colour, 'none')
if __name__=='__main__':
unittest.main()
More information about the Python-Dev
mailing list