In this documentation, it shows an example code:
class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x
Which only runs on Python 2.6/3.0. This blog post demonstrates how to add the property.setter in Python 2.5.
I made a small change. The following code will check the Python version and replace built-in property with new one.
import sys import __builtin__ # For Python 2.5-, this will enable the simliar property mechanism as in # Python 2.6+/3.0+. The code is based on # http://bruynooghe.blogspot.com/2008/04/xsetter-syntax-in-python-25.html if sys.version_info[:2] <= (2, 5): class property(property): def __init__(self, fget=None, fset=None, fdel=None, doc=None, *args, **kwargs): self.__doc__ = doc if doc else fget.__doc__ super(property, self).__init__(fget=fget, fset=fset, fdel=fdel, doc=doc, *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] def deleter(self, fdel): 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, self.fset, fdel, self.__doc__) return cls_ns[propname] __builtin__.property = property
This should make your code be compatible with both Python 2.5 and 2.6. Once decided to be 2.6 only, you will only need to remove the import statement. Actually, you don’t have to if you are lazy. :-)
Thanks for the fix. This really helped me since I had multiple users using my scripts on different python versions.
ReplyDelete