Sunday, June 6, 2010

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...

5 comments:

Nathan Horne said...

Wow, that is a really awesome way of handling properties! Thanks for showing that

Blazej said...

I got a SnippetEmu vim snippet for this if anyone is interested.

Kumaresan said...

How do I access doc variable, through the object.


obj = MyClass()

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

Ozgur said...

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...

GuildWars2Items said...

The consequences of today are determined by the actions of the past scarlet blade gold. To change your future, alter your decisions today scarlet blade gold, Experience is a hard teacher because she gives the test first, the lesson afterwards scarlet blade gold, but it takes character to keep you there.

I have a simple philosophy: Fill what's empty. Empty what's full. Scratch where it itches RS GP, Don't go around saying the world owes you a living. The world owes you nothing. It was here first RuneScape Gold, Being happy doesn't mean that everything is perfect. It means that rs gold you've decided to look beyond the imperfections.