[Python-Dev] properties and block statement

Duncan Booth duncan.booth at suttoncourtenay.org.uk
Wed Oct 19 11:11:16 CEST 2005


Stefan Rank <stefan.rank at ofai.at> wrote in news:4355EF41.4010803 at ofai.at:

> I think there is no need for a special @syntax for this to work.
> 
> I suppose it would be possible to allow a trailing block after any 
> function invocation, with the effect of creating a new namespace that 
> gets treated as containing keyword arguments.
> 

I suspect that without any syntax changes at all it will be possible (for 
some stack crawling implementation of 'propertycontext', and assuming 
nobody makes property objects immutable) to do:

   class C(object):
       with propertycontext() as x:
           doc = """ Yay for property x! """
           def fget(self):
               return self._x
           def fset(self, value):
               self._x = value

for inheritance you would have to specify the base property:

    class D(C):
       with propertycontext(C.x) as x:
           def fset(self, value):
               self._x = value+1


propertycontext could look something like:

import sys
@contextmanager
def propertycontext(parent=None):
    classframe = sys._getframe(2)
    cvars = classframe.f_locals
    marker = object()
    keys = ('fget', 'fset', 'fdel', 'doc')
    old = [cvars.get(key, marker) for key in keys]

    if parent:
        pvars = [getattr(parent, key) for key in
            ('fget', 'fset', 'fdel', '__doc__')]
    else:
        pvars = [None]*4

    args = dict(zip(keys, pvars))

    prop = property()
    try:
        yield prop
        for key, orig in zip(keys, old):
            v = cvars.get(key, marker)
            if v is not orig:
                args[key] = v
        prop.__init__(**args)
    finally:
        for k,v in zip(keys,old):
           if v is marker:
              if k in cvars:
                  del cvars[k]
           else:
               cvars[k] = v


More information about the Python-Dev mailing list