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:

Now you can use the聽 foo()聽 method like a property.

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?

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) 馃檨

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

2 thoughts on “Tripping Over Property Setters in Python”

    1. I’m probably the wrong person to ask 馃槄. When I was using it performance wasn’t a concern.

Leave a Reply

Your email address will not be published. Required fields are marked *