Python descriptor vs property

ZevGriner picture ZevGriner · Oct 11, 2012 · Viewed 10.9k times · Source

Possible Duplicate:
When and why might I assign an instance of a descriptor class to a class attribute in Python rather than use a property?

I'm confused as to when to use a property vs a descriptor. I read that a property is a specialized descriptor.

Can someone please post how this works?

Answer

millimoose picture millimoose · Oct 11, 2012

You should read the docs on what descriptors actually are. The Cliff's Notes version: descriptors are a low-level mechanism that lets you hook into an object's attributes being accessed. Properties are a high-level application of this; that is, properties are implemented using descriptors. Or, better yet, properties are descriptors that are already provided for you in the standard library.

If you need a simple way to return a computed value from an attribute read, or to call a function on an attribute write, use the @property decorator. The descriptor API is more flexible, but less convenient, and arguably "overkill" and non-idiomatic in this situation. It's useful for more advanced use cases, like implementing bound methods, or static and class methods; when you need to know, for example, if the attribute was accessed through the type object, or an instance of the type.