Using 'apply' as a decorator, to define constants

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Aug 22 05:03:39 EDT 2009


On Sat, 22 Aug 2009 08:09:52 +0100, Jonathan Fine wrote:

> Jonathan Gardner wrote:
>> On Aug 21, 9:09 am, alex23 <wuwe... at gmail.com> wrote:
>>> On Aug 21, 11:36 pm, Jonathan Fine <jf... at pytex.org> wrote:
>>>
>>> class ColourThing(object):
>>>     @apply
>>>     def rgb():
>>>         def fset(self, rgb):
>>>             self.r, self.g, self.b = rgb
>>>         def fget(self):
>>>             return (self.r, self.g, self.b)
>>>         return property(**locals())
>>>
>>>
>> This is brilliant. I am going to use this more often. I've all but
>> given up on property() since defining "get_foo", "get_bar", etc... has
>> been a pain and polluted the namespace.
> 
> 
> I think we can do better, with a little work.  And also solve the
> problem that 'apply' is no longer a builtin in Python3.

There's a standard idiom for that, using the property() built-in, for 
Python 2.6 or better.

Here's an example including a getter, setter, deleter and doc string, 
with no namespace pollution, imports, or helper functions or deprecated 
built-ins:

class ColourThing(object):
    @property
    def rgb(self):
        """Get and set the (red, green, blue) colours."""
        return (self.r, self.g, self.b)
    @rgb.setter
    def rgb(self, rgb):
        self.r, self.g, self.b = rgb
    @rgb.deleter
    def rgb(self):
        del self.r, self.g, self.b


 
-- 
Steven



More information about the Python-list mailing list