A new Property idiom in Python

There are really smart guys around the world, especially in python world. One of these guys (Sean Ross) suggested this to be used instead of the regular property in python:

"""
Rather than defining your get/set/del methods at the class level, as is usually done, e.g.

class MyClass(object):
def __init__(self):
self._foo = "foo"

def getfoo(self):
return self._foo
def setfoo(self, value):
self._foo = value
def delfoo(self):
del self._foo
foo = property(getfoo, setfoo, delfoo, "property foo's doc string")

I would like to suggest the following alternative idiom:
"""


class MyClass(object):
def __init__(self):
self._foo = "foo"
self._bar = "bar"

def foo():
doc = "property foo's doc string"
def fget(self):
return self._foo
def fset(self, value):
self._foo = value
def fdel(self):
del self._foo
return locals() # credit: David Niergarth
foo = property(**foo())

def bar():
doc = "bar is readonly"
def fget(self):
return self._bar
return locals()
bar = property(**bar())

I've started using these idiom and I'm happy to be able not to bloat my classes with getters and setters...

Comments

Nathan Horne said…
Wow, that is a really awesome way of handling properties! Thanks for showing that
Unknown said…
I got a SnippetEmu vim snippet for this if anyone is interested.
Unknown said…
How do I access doc variable, through the object.


obj = MyClass()

obj.foo.doc
or
obj.foo.__doc__
or
help(obj.foo)
help(MyClass.foo)

or

MyClass.foo.__doc__

prints the doc...

also there is another modification to the idiom in:

http://kbyanc.blogspot.com/2007/06/python-property-attribute-tricks.html

where the doc string of the property function is passed as the doc string of the property, a nice one...