Skip to content
Advertisement

How does the @property decorator work in Python?

I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator.

This example is from the documentation:

JavaScript

property‘s arguments are getx, setx, delx and a doc string.

In the code below property is used as a decorator. The object of it is the x function, but in the code above there is no place for an object function in the arguments.

JavaScript

How are the x.setter and x.deleter decorators created in this case?

Advertisement

Answer

The property() function returns a special descriptor object:

JavaScript

It is this object that has extra methods:

JavaScript

These act as decorators too. They return a new property object:

JavaScript

that is a copy of the old object, but with one of the functions replaced.

Remember, that the @decorator syntax is just syntactic sugar; the syntax:

JavaScript

really means the same thing as

JavaScript

so foo the function is replaced by property(foo), which we saw above is a special object. Then when you use @foo.setter(), what you are doing is call that property().setter method I showed you above, which returns a new copy of the property, but this time with the setter function replaced with the decorated method.

The following sequence also creates a full-on property, by using those decorator methods.

First we create some functions and a property object with just a getter:

JavaScript

Next we use the .setter() method to add a setter:

JavaScript

Last we add a deleter with the .deleter() method:

JavaScript

Last but not least, the property object acts as a descriptor object, so it has .__get__(), .__set__() and .__delete__() methods to hook into instance attribute getting, setting and deleting:

JavaScript

The Descriptor Howto includes a pure Python sample implementation of the property() type:

JavaScript
Advertisement