Friday, March 20, 2009

Python property snippet for YASnippet

I have recently begun using YASnippet for Emacs (AquaMacs on Mac actually). YASnippet adds powerful snippet support to Emacs reminiscent of the snippet support in TextMate. Using YASnippet you may for example in Python mode type "class" and then hit the Tab-key which would expand into a class-definition snippet where all of the boiler-plate code has already been written for you.

While YASnippet is quite powerful is does lack a number of standard snippets (or templates) in its standard library. For example I was missing a proper Python property snippet, so I wrote one:

# contributor: Mads D. Kristensen
# name: prop
# --
def ${1:foo}():
doc = """${2:Doc string}"""
def fget(self):
return self._$1
def fset(self, value):
self._$1 = value
def fdel(self):
del self._$1
return locals()
$1 = property(**$1())

$0

Using this snippet you can write "prop" and press the Tab-key. Now you only need to provide a name for the property and, if you like, a doc string for the property. The snippet then creates a getter, setter, and deleter method for the property.

No comments:

Post a Comment