devork

E pur si muove

@x.setter syntax in Python 2.5

Friday, April 11, 2008

The new property.setter syntax in Python 2.6 and 3.0 looks very clean to me. So I couldn't wait and wanted it in Python 2.5. With the help of comp.lang.python I finally got there (thanks especially to Arnaud Delobelle):

_property = property

class property(property):
    def __init__(self, fget, *args, **kwargs):
        self.__doc__ = fget.__doc__
        super(property, self).__init__(fget, *args, **kwargs)

    def setter(self, fset):
        cls_ns = sys._getframe(1).f_locals
        for k, v in cls_ns.iteritems():
            if v == self:
                propname = k
                break
        cls_ns[propname] = property(self.fget, fset,
                                    self.fdel, self.__doc__)
        return cls_ns[propname]

The __init__() wrapper is needed to get __doc__ set properly (this surprised me). The whole cls_ns stuff and the loop are required since the properties are defined in C and their fset attribute is read-only. Which is why the entire property needs to be replaced. The implementation of deleter() can now be regarded as an exercise to the reader...

3 comments:

Floris Bruynooghe said...

That is useful, can't believe I haven't seen this before! But having it builtin is very useful and what I came up with is going to become builtin...

Not that I am going to comment which is the nicer syntax.

New comments are not allowed.

Subscribe to: Post Comments (Atom)