Tripping Over Property Setters in Python

In Python there is a simple way to make methods behave like properties using the @property decorator. But this only covers the getter side of things. What if you want to have a setter function for this “property”? Well there is a way. 🙂
Consider the following example:

import json

class SomeModel(object):
  _foo = '{"foo":["bar", "baz"]}'

  @property
  def foo(self):
    return json.loads(self._foo)

  @foo.setter
  def foo_setter(self, new_value):
    self._foo = json.dumps(new_value)

m = SomeModel()

Now you can use the 

foo()

  method like a property.

>>> m.foo
{u'foo': [u'bar', u'baz']}

This is a simple way to have a property contain a JSON string but access it as a Python dict, doing (de-)serialization on the fly.
So what if you want to set the value using a dict?

>>> m.foo = ["foo", "bar"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

This is can easily trip up even seasoned Python developers. I’ve read code that did exactly this and I (as a novice) had to find out why the code failed. m(
The solution is quite simple … but “non-obvious” (as in: I wouldn’t have thought of that without consulting the docs) 🙁

  @foo.setter
  def foo(self, new_value)
    self._foo = json.dumps(new_value)

Notice the method name? The setter and the getter methods have to have the same name!

Convert any file VLC can play to mp3

I just felt the need for a script that could extract the audio track of a video, transcode it and save it as an mp3 file … 2 hours later I was finished (get the Gist). 😀 It uses VLC to do hard work. 😉

Thanks to Kris Hom for the inspiration. 🙂

Update 2014-03-01:

  • Check whether VLC is installed
  • Should also work on Linux now
  • Increase default bit rate to 192kbit/s
  • Fixed bug where the file/playlist would repeat endlessly

Update 2014-11-05:

  • Also look for VLC in “~/Application/”

Update 2016-03-05

The Y Combinator

I take my head off to Jim, that’s a great way to approach a weird intersection of mathematics and programming. 😉 For those who are curious … he uses a very simple mathematical algorithm to explore how you can express recursions in Lambda calculus and thus “derives” the Y combinator.

Totally useless, but worth every minute. 😉