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 to riyad Cancel reply

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