Using 'apply' as a decorator, to define constants
Jonathan Fine
jfine at pytex.org
Sat Aug 22 03:09:52 EDT 2009
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.
Here's my suggestion:
===
import wibble # Informs reader we're doing something special here.
class ColourThing(object):
@wibble.property
def rgb():
'''This is the docstring for the property.'''
def fset(self, rgb):
self.r, self.g, self.b = rgb
def fget(self):
return (self.r, self.g, self.b)
return locals()
===
And here's wibble.property()
===
_property = property # Avoid collision.
def property(fn):
return _property(doc=fn.__doc__, **fn())
===
We can add apply() to the wibble module. By the way, 'wibble' is a
placeholder to the real name. Any suggestions?
--
Jonathan
More information about the Python-list
mailing list