Decorative Python

In my code for DrProject/REST, I rather like a trivial 2 lines of Python that ever so thinly wraps around property and is used for decoration.


def Property(func):
   return property(doc=func.__doc__, *func())

If it’s not immediately clear what this does, you’re new to Python decorators. Here’s an silly, useless, but otherwise insightful example:


class Test(object):

   def __init__(self, value):
      self.__data = value

   @Property
   def data():
      '''Here is my docstring'''
      def fget(self):
         return self.__data
      def fset(self, value):
         self.__data = value
      def fdel(self):
         raise NotImplementedError, "Cannot delete"
      return fget, fset, fdel

That’s all,
Dave

Leave a Reply

You must be logged in to post a comment.