<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>learning python &#187; descriptors</title>
	<atom:link href="http://www.learningpython.com/tag/descriptors/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.learningpython.com</link>
	<description>one man's journey into python...</description>
	<lastBuildDate>Wed, 21 Sep 2011 03:08:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Introducing Descriptors and Properties</title>
		<link>http://www.learningpython.com/2010/04/25/introducing-descriptors-and-properties/</link>
		<comments>http://www.learningpython.com/2010/04/25/introducing-descriptors-and-properties/#comments</comments>
		<pubDate>Mon, 26 Apr 2010 01:21:51 +0000</pubDate>
		<dc:creator>selsine</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[Python Magazine]]></category>
		<category><![CDATA[descriptors]]></category>
		<category><![CDATA[properties]]></category>

		<guid isPermaLink="false">http://www.learningpython.com/?p=186</guid>
		<description><![CDATA[Note: This article was first published the May 2008 issue of Python Magazine Introducing Descriptors and Properties Mark Mruss New-style classes were introduced to Python with the release of Python 2.2. And with these new-style classes came descriptors and properties. This article will introduce the descriptor protocol, descriptors, and properties. Introduction New-style classes were introduced [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.learningpython.com%2F2010%2F04%2F25%2Fintroducing-descriptors-and-properties%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.learningpython.com%2F2010%2F04%2F25%2Fintroducing-descriptors-and-properties%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Note: This article was first published the <a href="http://www.pythonmagazine.com/c/issue/view/69">May 2008</a> issue of <a href="http://www.pythonmagazine.com/">Python Magazine</a></p>
<p><strong>Introducing Descriptors and Properties</strong></p>
<p><strong>Mark Mruss</strong></p>
<p>New-style classes were introduced to Python with the release of Python 2.2. And with these new-style classes came descriptors and properties. This article will introduce the descriptor protocol, descriptors, and properties.</p>
<h2>Introduction</h2>
<p>New-style classes were introduced to Python with the release of Python 2.2.  A new-style class is any class that is derived from the <code>object</code> base class. New-style classes give Python programmers many new (and initially confusing) features. One such feature is the descriptor protocol, and more specifically descriptors themselves.</p>
<p>Descriptors give Python programmers the ability to easily and efficiently create &#8220;managed attributes&#8221;. Managed attributes can be thought of as attributes that are not accessed directly. Instead their access is &#8220;managed&#8221; by something else, generally a class or a function.</p>
<p>If you haven&#8217;t come across this before you are probably wondering why one would want to manage attribute access? One reason might be that you don&#8217;t want people to be able to delete the attribute. Another reason may be that you need to ensure that your attribute data is always valid. Or perhaps attribute <code>x</code> is based on attribute <code>y</code>, so every time the value of <code>y</code> changes you want to update the value of <code>x</code>.  From these few examples you can see the many possible cases where you might want to control access to certain attributes.</p>
<p>For those of you familiar with other programming languages, this type of access is often referred to as &#8220;getters and setters&#8221;.  In many language, implementing &#8220;getters and setters&#8221; means using private variables and public functions that get and set the variable&#8217;s value. Since Python doesn&#8217;t (really) have private variables, the descriptor protocol is basically a built-in and Python-ic way to way to achieve something similar.</p>
<p>This article will introduce you to the descriptor protocol, descriptors, and properties. It will focus on demonstrating how to use them to create managed attributes. Since the descriptor protocol requires new-style classes, all of the examples in this article require Python 2.2 or newer.</p>
<p><span id="more-186"></span></p>
<h2>A few definitions</h2>
<p>Before moving forward, it is important to understand a few related terms. These terms will introduce some basic concepts and help you follow along with the remainder of the article.</p>
<p><strong>descriptor protocol</strong> &#8211; The following three methods make up the descriptor protocol: <code>__get__</code>, <code>__set__</code>, and <code>__delete__</code>.</p>
<p><strong>descriptor</strong> &#8211; An &#8220;object attribute with <code>binding behavior</code>, one whose attribute access has been overridden by methods in the descriptor protocol.&#8221; <a href="http://docs.python.org/ref/descriptor-invocation.html">[1]</a> In other words an &#8220;attributes whose usage resembles attribute access, but whose implementation uses method calls.&#8221;<a href="http://www.python.org/download/releases/2.2/descrintro/#property">[2]</a></p>
<p><strong>data descriptor</strong> &#8211; A descriptor with the <code>__get__</code> and <code>__set__</code> methods of the descriptor protocol defined.</p>
<p><strong>non-data descriptor</strong> &#8211; A descriptor with only the <code>__get__</code>  method of the descriptor protocol defined. &#8220;Python methods (including staticmethod() and classmethod()) are implemented as non-data descriptors.&#8221; <a href="http://docs.python.org/ref/descriptor-invocation.html">[3]</a></p>
<p><strong>property</strong> &#8211; A built-in type that implements the descriptor protocol and allows you to easily create data descriptors.</p>
<p>Don&#8217;t worry if you don&#8217;t fully understand these definitions, the remainder of this article will hopefully clarify any confusion you have.</p>
<h2>The Descriptor Protocol</h2>
<p>Let&#8217;s take a closer look at the descriptor protocol and see how we can use it to create a descriptor.  As previously mentioned, the descriptor protocol is made up of three methods: <code>__get__</code>, <code>__set__</code>, and <code>__delete__</code>.  These methods have specific signatures and they are as follows, where <code>self</code> is the class that owns the methods:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">__get__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-code">, </span><span class="hl-identifier">owner</span><span class="hl-brackets">)
</span><span class="hl-identifier">__set__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-code">, </span><span class="hl-identifier">value</span><span class="hl-brackets">)
</span><span class="hl-identifier">__delete__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-brackets">)</span></pre></div></div>
<p>These three methods represent the three basic operations that you perform on attributes in general: querying the value of that attribute; assigning a value to it; and, (very rarely) deleting it. They work as follows:</p>
<ul>
<li>
The <code>__get__</code> method is called when the attributes value is being queried.  The <code>__get__</code> method should return the (computed) attribute value or raise an AttributeError exception.&#8221; <a href="http://docs.python.org/ref/descriptors.html">[4]</a> This is where access to the attribute&#8217;s value is managed.
</li>
<li>
The <code>__set__</code> method is used in the assignment operation. It is called when we want to set the attribute value. This is where you can control what values, or types of values are being assigned to your attribute.
</li>
<li>Finally, the <code>__delete__</code> method is called when we want to delete the attribute. Here you can (rarely) decide whether or not to delete the attribute.
</li>
</ul>
<p>There are also three different parameters passed to the three methods (excluding the standard <code>self</code> parameter for methods that belong to a class):</p>
<ul>
<li>
<code>owner</code> &#8211; This &#8220;is always the owner class.&#8221; <a href="http://docs.python.org/ref/descriptors.html">[5]</a> This means that it is the actual class, and not an instance of the class. So if the descriptor is in a class called <code>MyClass</code>, <code>owner</code> will be that class.
</li>
<li>
<code>instance</code> &#8211; An instance of class type <code>owner</code>. It is &#8220;the instance that the attribute was accessed through&#8221; <a href="http://docs.python.org/ref/descriptors.html">[6]</a>, or <code>None</code> if the attribute is being accessed through the class (<code>owner</code>) instead of an instance.
</li>
<li>
<code>value</code>- The value that the attribute is being set to.
</li>
</ul>
<p>This difference between <code>owner</code> and <code>instance</code> might be a bit confusing, so let&#8217;s look at a quick example. LetÃ¢Â€Â™s say we have a descriptor <code>my_descriptor</code> in the class <code>MyClass</code>, if we were to run the following code:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">my_class_instance</span><span class="hl-default"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">()
</span><span class="hl-reserved">print </span><span class="hl-identifier">my_class_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_descriptor</span></pre></div></div>
<p>The second line queries the descriptors value and results in the <code>__get__</code> method being called with the <code>instance</code> parameter being <code>my_class_instance</code>. The <code>owner</code> parameter will be the <code>MyClass</code> class.</p>
<p><strong>Note:</strong> Notice that we treat the descriptor <code>my_descriptor</code> as though it is a normal attribute. We don&#8217;t call <code>print my_class_instance.my_descriptor.__get__(my_class, MyClass)</code>. This is what was meant by: &#8220;attributes whose usage resembles attribute access, but whose implementation uses method calls.&#8221;<a href="http://www.python.org/download/releases/2.2/descrintro/#property">[7]</a></p>
<p>If the following code were run:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-reserved">print </span><span class="hl-identifier">MyClass</span><span class="hl-default">.</span><span class="hl-identifier">my_descriptor</span></pre></div></div>
<p>The <code>__get__</code> method will again be called. This time the <code>instance</code> parameter will be <code>None</code> and the <code>owner</code> parameter will be the <code>MyClass</code> class.</p>
<p><strong>Note:</strong> Only the <code>__get__</code> method has the <code>owner</code> parameter. This means that it is the only function in the descriptor protocol that can be accessed through the class. Setting and deleting the descriptor through the class actually changes <strong>what</strong> the variable is. For example, if we tried to assign the numeric value 2 to a descriptor variable using the class, we would not access the descriptors <code>__set__</code> method. Instead we would change the type of the variable from a descriptor to an integer with the value of 2.</p>
<h2>A Simple Descriptor Example</h2>
<p>A simple &#8220;transparent&#8221; descriptor example can be found in Listing 1. The first thing to notice in the code is that both the <code>SimpleDescriptor</code> and <code>MyClass</code> classes are &#8220;new-style&#8221; classes because they are derived from <code>object</code>. This is important because, as mentioned above, descriptors only work with &#8220;new-style&#8221; classes. The second point to notice is that the descriptor has class scope as opposed to instance scope. There are also two extra print statements included in the code. They are there to let us follow the execution a little more easily.</p>
<p><strong>Listing 1</strong></p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">class </span><span class="hl-identifier">SimpleDescriptor</span><span class="hl-brackets">(</span><span class="hl-identifier">object</span><span class="hl-brackets">)</span><span class="hl-default">:

    </span><span class="hl-reserved">def </span><span class="hl-identifier">__get__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-code">, </span><span class="hl-identifier">owner</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-comment"># Check if the value has been set
        </span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-reserved">not </span><span class="hl-builtin">hasattr</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-quotes">&quot;</span><span class="hl-string">_value</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">))</span><span class="hl-default">:
            </span><span class="hl-reserved">raise AttributeError
        print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Getting value: %s</span><span class="hl-quotes">&quot;</span><span class="hl-default"> % </span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">_value
        </span><span class="hl-reserved">return </span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">_value

    </span><span class="hl-reserved">def </span><span class="hl-identifier">__set__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-code">, </span><span class="hl-identifier">value</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Setting to %s</span><span class="hl-quotes">&quot;</span><span class="hl-default"> % </span><span class="hl-identifier">value
        self</span><span class="hl-default">.</span><span class="hl-identifier">_value</span><span class="hl-default"> = </span><span class="hl-identifier">value

    </span><span class="hl-reserved">def </span><span class="hl-identifier">__delete__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-identifier">del</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">_value</span><span class="hl-brackets">)

</span><span class="hl-reserved">class </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">(</span><span class="hl-identifier">object</span><span class="hl-brackets">)</span><span class="hl-default">:
    </span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-identifier">SimpleDescriptor</span><span class="hl-brackets">()</span></pre></div></div>
<p>Using Listing 1 to execute the following code:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">my_instance</span><span class="hl-default"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">()
</span><span class="hl-identifier">my_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-number">416
</span><span class="hl-reserved">print </span><span class="hl-identifier">my_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value</span></pre></div></div>
<p>The output would be the following:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">Setting to </span><span class="hl-number">416
</span><span class="hl-identifier">Getting value</span><span class="hl-default">: </span><span class="hl-number">416
416</span></pre></div></div>
<p>As you can see the second line (<code>my_instance.data_descriptor = 416</code>) calls the <code>__set__</code> method and sets the _value attribute. When we call <code>print my_instance.data_descriptor</code> the <code>__get__</code>, method is called and the <code>_value</code> attribute is returned.</p>
<h2>The Problem with the Simple Example</h2>
<p>The previous example may look like a perfectly good descriptor, but there is something wrong with it. Take a look at what happens when we runs this new code:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">my_instance</span><span class="hl-default"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">() </span><span class="hl-comment">#Create the first instance
</span><span class="hl-identifier">my_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-number">416 </span><span class="hl-comment">#Set its' value
</span><span class="hl-identifier">my_second_instance</span><span class="hl-default"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">() </span><span class="hl-comment">#Create the second instance
</span><span class="hl-identifier">my_second_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-number">204 </span><span class="hl-comment">#Set its' value
</span><span class="hl-reserved">print </span><span class="hl-identifier">my_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value </span><span class="hl-comment">#What was the fist instance's value?</span></pre></div></div>
<p>We get the following output:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">Setting to </span><span class="hl-number">416
</span><span class="hl-identifier">Setting to </span><span class="hl-number">204
</span><span class="hl-identifier">Getting value</span><span class="hl-default">: </span><span class="hl-number">204
204</span></pre></div></div>
<p>Notice that when we set the second instance&#8217;s <code>my_value</code> descriptor to be 204, we are also setting the first instances. This is because <code>my_value</code> has class scope, so both instances (and the class itself) share the same instance of the <code>SimpleDescriptor</code> class. Since <code>SimpleDescriptor</code> only stores one value, they all actually share the same value. We will get the same results if we check what the classes value of <code>my_value</code> is:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">my_instance</span><span class="hl-default"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">() </span><span class="hl-comment">#Create the first instance
</span><span class="hl-identifier">my_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-number">416 </span><span class="hl-comment">#Set its' value
</span><span class="hl-identifier">my_second_instance</span><span class="hl-default"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">() </span><span class="hl-comment">#Create the second instance
</span><span class="hl-identifier">my_second_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-number">204 </span><span class="hl-comment">#Set its' value
</span><span class="hl-reserved">print </span><span class="hl-identifier">MyClass</span><span class="hl-default">.</span><span class="hl-identifier">my_value </span><span class="hl-comment">#What's the classes value?</span></pre></div></div>
<p>We get the following results:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">Setting to </span><span class="hl-number">416
</span><span class="hl-identifier">Setting to </span><span class="hl-number">204
</span><span class="hl-identifier">Getting value</span><span class="hl-default">: </span><span class="hl-number">204
204</span></pre></div></div>
<p>In the last line of the code (<code>print MyClass.my_value #What's the classes value?</code>) we simply use the class (ignoring both instances) in order to get the value of <code>my_data</code>. This will be an instance where the <code>__get__</code> function will be called with the <code>instance</code> parameter set to <code>None</code>.</p>
<p><strong>Note:</strong> This is not a problem if you want to share the value across all instances.</p>
<h2>The Solution to the Problem</h2>
<p>In order to get around this issue, you have to remember that if you want values unique to each instance your descriptors must store values that are unique to each instance. This can be in the instance itself, in dictionary in the descriptor, or perhaps in a text file. Just make sure that the value is unique to each instance. Though it seems like a simple solution, in practice a suitable solution for all cases is difficult to implement. As a result you should probably pick a specific implementation for your specific situations.</p>
<p>Using each instance as a key, one can store the value in a dictionary in the descriptor itself. The problem with this solution should be obvious to programmers familiar with Python dictionaries: only immutable types can be used as keys. This is fine if you know what object you are working with, but what about in the future when you want to add a descriptor to your sub-classed list?</p>
<p>Another solution is to store the value in the instance itself. You can do this by easily adding the value to the instance&#8217;s <code>__dict__</code>. The limitation is that the descriptor need to be given a suitable key so that there is no collision with anything already in the instance&#8217;s <code>__dict__</code>.</p>
<p>Listing 2 shows a solution to the problem from the previous section where the value is stored in the instance&#8217;s <code>__dict__</code>. Values are indexed using a key name provided during the creation of the descriptor.  Aside from where we store the value, there is little difference between Listing 1 and Listing 2.  Notice that the value name is a converted into a string. This is done to ensure that it can be used as a key.</p>
<p><strong>Listing 2</strong></p>
<div class="hl-surround" style="height:280px;"><div class="hl-main"><pre><span class="hl-reserved">class </span><span class="hl-identifier">FixedDescriptor</span><span class="hl-brackets">(</span><span class="hl-identifier">object</span><span class="hl-brackets">)</span><span class="hl-default">:

</span><span class="hl-reserved">def </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">value_name</span><span class="hl-brackets">)</span><span class="hl-default">:
    </span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">value_name</span><span class="hl-default"> = </span><span class="hl-builtin">str</span><span class="hl-brackets">(</span><span class="hl-identifier">value_name</span><span class="hl-brackets">)

</span><span class="hl-reserved">def </span><span class="hl-identifier">__get__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-code">, </span><span class="hl-identifier">owner</span><span class="hl-brackets">)</span><span class="hl-default">:
    </span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-identifier">instance </span><span class="hl-reserved">is None</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-reserved">raise AttributeError
    </span><span class="hl-identifier">elif </span><span class="hl-brackets">(</span><span class="hl-reserved">not </span><span class="hl-identifier">instance</span><span class="hl-code">.</span><span class="hl-identifier">__dict__</span><span class="hl-code">.</span><span class="hl-identifier">has_key</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">value_name</span><span class="hl-brackets">))</span><span class="hl-default">:
        </span><span class="hl-reserved">raise AttributeError
    return </span><span class="hl-identifier">instance</span><span class="hl-default">.</span><span class="hl-identifier">__dict__</span><span class="hl-brackets">[</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">value_name</span><span class="hl-brackets">]

    </span><span class="hl-reserved">def </span><span class="hl-identifier">__set__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-code">, </span><span class="hl-identifier">value</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Setting to %s</span><span class="hl-quotes">&quot;</span><span class="hl-default"> % </span><span class="hl-identifier">value
        instance</span><span class="hl-default">.</span><span class="hl-identifier">__dict__</span><span class="hl-brackets">[</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">value_name</span><span class="hl-brackets">]</span><span class="hl-default"> = </span><span class="hl-identifier">value

    </span><span class="hl-reserved">def </span><span class="hl-identifier">__delete__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-identifier">instance</span><span class="hl-code">.</span><span class="hl-identifier">__dict__</span><span class="hl-code">.</span><span class="hl-identifier">has_key</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">value_name</span><span class="hl-brackets">))</span><span class="hl-default">:
            </span><span class="hl-identifier">del</span><span class="hl-brackets">(</span><span class="hl-identifier">instance</span><span class="hl-code">.</span><span class="hl-identifier">__dict__</span><span class="hl-brackets">[</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">value_name</span><span class="hl-brackets">])


</span><span class="hl-reserved">class </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">(</span><span class="hl-identifier">object</span><span class="hl-brackets">)</span><span class="hl-default">:
    </span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-identifier">FixedDescriptor</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">__value</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span></pre></div></div>
<p>The major usage difference between Listing 1 and Listing 2 is the fact that the <code>__get__</code> method no longer works at class level; it only works at instance level. This should be obvious since this solution stores the value in the instance.  If there is no instance, we have nowhere to store the value!  If you attempt to access the descriptor at class level (the first if statement) an attribute error will be raised:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">def </span><span class="hl-identifier">__get__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-code">, </span><span class="hl-identifier">owner</span><span class="hl-brackets">)</span><span class="hl-default">:
    </span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-identifier">instance </span><span class="hl-reserved">is None</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-reserved">raise AttributeError
    </span><span class="hl-identifier">elif </span><span class="hl-brackets">(</span><span class="hl-reserved">not </span><span class="hl-identifier">instance</span><span class="hl-code">.</span><span class="hl-identifier">__dict__</span><span class="hl-code">.</span><span class="hl-identifier">has_key</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">value_name</span><span class="hl-brackets">))</span><span class="hl-default">:
        </span><span class="hl-reserved">raise AttributeError
    return </span><span class="hl-identifier">instance</span><span class="hl-default">.</span><span class="hl-identifier">__dict__</span><span class="hl-brackets">[</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">value_name</span><span class="hl-brackets">]</span></pre></div></div>
<h2>Easy Data Descriptors with Properties</h2>
<p>The descriptor provided in Listing 2 will work for many situations but for my money the easiest way to implement data descriptors is to use the <code>property</code> type. I would recommend using it unless you need the same descriptor across many different classes or attributes (i.e. for type validation). Properties can be thought of as a simple and easy way to create data descriptors. The <code>property</code> type implements the descriptor protocol and gets around the problem of where to store the descriptor value in an easy way: it lets the class that created the descriptor deal with it.</p>
<p>The full signature of the <code>property</code> function is as follows:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre><span class="hl-builtin">property</span><span class="hl-brackets">(</span><span class="hl-identifier">fget</span><span class="hl-code">=</span><span class="hl-reserved">None</span><span class="hl-code">, </span><span class="hl-identifier">fset</span><span class="hl-code">=</span><span class="hl-reserved">None</span><span class="hl-code">, </span><span class="hl-identifier">fdel</span><span class="hl-code">=</span><span class="hl-reserved">None</span><span class="hl-code">, </span><span class="hl-identifier">doc</span><span class="hl-code">=</span><span class="hl-reserved">None</span><span class="hl-brackets">)</span></pre></div></div>
<p>Where <code>fget</code>, <code>fset</code>, <code>fdel</code> are methods that will be called when the <code>__get__</code>, <code>__set__</code>, and <code>__del__</code> members of the descriptor protocol are called. The <code>doc</code> parameter is a string that will be used as the docstring for the descriptor.  If the <code>doc</code> parameter is not specified, the docstring of the <code>fget</code> method is used.</p>
<p>The signature of the <code>fget</code>, <code>fset</code>, <code>fdel</code> functions are as follows:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">fget</span><span class="hl-brackets">(</span><span class="hl-identifier">instance</span><span class="hl-brackets">)
</span><span class="hl-identifier">fset</span><span class="hl-brackets">(</span><span class="hl-identifier">instance</span><span class="hl-code">, </span><span class="hl-identifier">value</span><span class="hl-brackets">)
</span><span class="hl-identifier">fdel</span><span class="hl-brackets">(</span><span class="hl-identifier">instance</span><span class="hl-brackets">)</span></pre></div></div>
<p>In the three signatures, <code>instance</code> is a reference to the object that owns the property attribute. This is the same instance that gets passed to the descriptor protocol.  Since <code>instance</code> is the first parameter of each method, these are, for all intents and purposes, member methods of a class. The <code>value</code> parameter is the same as the <code>value</code> parameter that is passed to the <code>__set__</code> method. It is what we are setting the attribute to.</p>
<p>The basic way to implement properties can be seen in Listing 3. As you can see, what we do for a property is very similar to what we did for our initial descriptor in Listing 1. We set up the three functions necessary for the descriptor protocol, and then use them to create our property attribute.  Creating the property is very simple:</p>
<p><strong>Listing 3</strong></p>
<div class="hl-surround" style="height:280px;"><div class="hl-main"><pre><span class="hl-reserved">class </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">(</span><span class="hl-identifier">object</span><span class="hl-brackets">)</span><span class="hl-default">:
    </span><span class="hl-comment">#Create the fget, fset, and fdel methods
    </span><span class="hl-reserved">def </span><span class="hl-identifier">__get_value</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Getting value: %s</span><span class="hl-quotes">&quot;</span><span class="hl-default"> % </span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">__value
        </span><span class="hl-reserved">return </span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">__value

    </span><span class="hl-reserved">def </span><span class="hl-identifier">__set_value</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">value</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-reserved">print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Setting to %s</span><span class="hl-quotes">&quot;</span><span class="hl-default"> % </span><span class="hl-identifier">value
        self</span><span class="hl-default">.</span><span class="hl-identifier">__value</span><span class="hl-default"> = </span><span class="hl-identifier">value

    </span><span class="hl-reserved">def </span><span class="hl-identifier">__del_value</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-identifier">del</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">__value</span><span class="hl-brackets">)

    </span><span class="hl-comment">#Create the property
    </span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-builtin">property</span><span class="hl-brackets">(</span><span class="hl-identifier">__get_value</span><span class="hl-code">
            , </span><span class="hl-identifier">__set_value</span><span class="hl-code">
            , </span><span class="hl-identifier">__del_value</span><span class="hl-code">
            , </span><span class="hl-quotes">&quot;</span><span class="hl-string">This is my property</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)

    </span><span class="hl-reserved">def </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">value</span><span class="hl-code">=</span><span class="hl-number">0</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-identifier">value</span></pre></div></div>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-builtin">property</span><span class="hl-brackets">(</span><span class="hl-identifier">__get_value</span><span class="hl-code">
        , </span><span class="hl-identifier">__set_value</span><span class="hl-code">
        , </span><span class="hl-identifier">__del_value</span><span class="hl-code">
        , </span><span class="hl-quotes">&quot;</span><span class="hl-string">This is my property</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span></pre></div></div>
<h2>Make Data Attributes Data-Descriptors</h2>
<p>A common reason to use descriptors is to create read-only attributes. This means allowing callers to get (or access) an attribute&#8217;s value, but not allowing them to set its&#8217; value. At first glance it seems as though one can accomplish this by using descriptors with only the <code>__get__</code> method defined, i.e. a &#8220;non-data descriptor&#8221;.</p>
<p>While this seems to create a read-only descriptor attribute, it actually does nothing of the sort. Instead of using the descriptor&#8217;s <code>__set__</code> function for the assignment operation (since no <code>__set__</code> function is defined), the default Python assignment operation is used. This means that instead of stopping the assignment operation, a new attribute will be created in the instance (remember that descriptors have class scope) having the same name as the descriptor attribute and taking precedence in future operations.</p>
<p>This may be a bit confusing so let&#8217;s look at the example in Listing 4. It&#8217;s very much like our previous descriptor examples except it does not specify the <code>__set__</code> and <code>__del__</code> functions. LetÃ¢Â€Â™s look at what happens when we try to use this as though it were a read-only attribute:</p>
<p><strong>Listing 4</strong></p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">class </span><span class="hl-identifier">WonkyDescriptor</span><span class="hl-brackets">(</span><span class="hl-identifier">object</span><span class="hl-brackets">)</span><span class="hl-default">:
    </span><span class="hl-quotes">&quot;&quot;&quot;</span><span class="hl-string">This Descriptor isn't read only</span><span class="hl-quotes">&quot;&quot;&quot;
    </span><span class="hl-reserved">def </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">value_name</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">value_name</span><span class="hl-default"> = </span><span class="hl-builtin">str</span><span class="hl-brackets">(</span><span class="hl-identifier">value_name</span><span class="hl-brackets">)

    </span><span class="hl-reserved">def </span><span class="hl-identifier">__get__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">instance</span><span class="hl-code">, </span><span class="hl-identifier">owner</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-identifier">if </span><span class="hl-brackets">(</span><span class="hl-identifier">instance </span><span class="hl-reserved">is None</span><span class="hl-brackets">)</span><span class="hl-default">:
            </span><span class="hl-reserved">raise AttributeError
        </span><span class="hl-identifier">elif </span><span class="hl-brackets">(</span><span class="hl-reserved">not </span><span class="hl-identifier">instance</span><span class="hl-code">.</span><span class="hl-identifier">__dict__</span><span class="hl-code">.</span><span class="hl-identifier">has_key</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">value_name</span><span class="hl-brackets">))</span><span class="hl-default">:
            </span><span class="hl-reserved">raise AttributeError
        print </span><span class="hl-quotes">&quot;</span><span class="hl-string">Getting a value</span><span class="hl-quotes">&quot;
        </span><span class="hl-reserved">return </span><span class="hl-identifier">instance</span><span class="hl-default">.</span><span class="hl-identifier">__dict__</span><span class="hl-brackets">[</span><span class="hl-identifier">self</span><span class="hl-code">.</span><span class="hl-identifier">value_name</span><span class="hl-brackets">]

</span><span class="hl-reserved">class </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">(</span><span class="hl-identifier">object</span><span class="hl-brackets">)</span><span class="hl-default">:

    </span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-identifier">WonkyDescriptor</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">_value</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)

    </span><span class="hl-reserved">def </span><span class="hl-identifier">__init__</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-code">, </span><span class="hl-identifier">value</span><span class="hl-brackets">)</span><span class="hl-default">:
        </span><span class="hl-comment">#initial value
        </span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">_value</span><span class="hl-default"> = </span><span class="hl-identifier">value</span></pre></div></div>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">my_instance</span><span class="hl-default"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">(</span><span class="hl-number">23</span><span class="hl-brackets">) </span><span class="hl-comment">#Create the first instance
</span><span class="hl-reserved">print </span><span class="hl-identifier">my_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value
my_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-quotes">&quot;</span><span class="hl-string">Don't set me!</span><span class="hl-quotes">&quot;
</span><span class="hl-reserved">print </span><span class="hl-identifier">my_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value</span></pre></div></div>
<p>When we run this, we get the following output:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">Getting a value
</span><span class="hl-number">23
</span><span class="hl-identifier">Don</span><span class="hl-quotes">'</span><span class="hl-string">t set me!</span></pre></div></div>
<p>As you can see we did not succeed in creating a read-only attribute, instead something else happened. The &#8220;Getting a value&#8221; string is printed out when we print out <code>my_value</code> for the first time. This means that we are accessing the value through the descriptor. We then set the value of the descriptor attribute and print out that new value. Since &#8220;Getting a value&#8221; isn&#8217;t printed out a second time, we know that the descriptor&#8217;s <code>__get__</code> method is not accessed when the second print statement is called.</p>
<p>Let&#8217;s take a closer look at what is happening using the following code, which prints out the instance&#8217;s <code>__dict__</code>:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-identifier">my_instance</span><span class="hl-default"> = </span><span class="hl-identifier">MyClass</span><span class="hl-brackets">(</span><span class="hl-number">23</span><span class="hl-brackets">) </span><span class="hl-comment">#Create the first instance
</span><span class="hl-reserved">print </span><span class="hl-identifier">my_instance</span><span class="hl-default">.</span><span class="hl-identifier">__dict__
my_instance</span><span class="hl-default">.</span><span class="hl-identifier">my_value</span><span class="hl-default"> = </span><span class="hl-quotes">&quot;</span><span class="hl-string">Don't set me!</span><span class="hl-quotes">&quot;
</span><span class="hl-reserved">print </span><span class="hl-identifier">my_instance</span><span class="hl-default">.</span><span class="hl-identifier">__dict__</span></pre></div></div>
<p>This results in the following, which explains what is happening:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-default">{</span><span class="hl-quotes">'</span><span class="hl-string">_value</span><span class="hl-quotes">'</span><span class="hl-default">: </span><span class="hl-number">23</span><span class="hl-default">}
{</span><span class="hl-quotes">'</span><span class="hl-string">_value</span><span class="hl-quotes">'</span><span class="hl-default">: </span><span class="hl-number">23</span><span class="hl-default">, </span><span class="hl-quotes">'</span><span class="hl-string">my_value</span><span class="hl-quotes">'</span><span class="hl-default">: </span><span class="hl-quotes">&quot;</span><span class="hl-string">Don't set me!</span><span class="hl-quotes">&quot;</span><span class="hl-default">}</span></pre></div></div>
<p>When we first access the <code>__dict__</code> we see our value indexed by the <code>_value</code> key that we told the descriptor to use. Now look at the second <code>__dict__</code>. The old value is still there, but so is a new value <code>my_value</code>. When we assigned &#8220;Don&#8217;t set me!&#8221; to <code>my_value</code>, we didn&#8217;t overwrite the descriptor attribute at class scope, we created a new instance attribute! And it is not exactly a read-only attribute.</p>
<p>In order to create a read-only attribute, you need to create a <code>data descriptor</code> where the <code>__set__</code> method raises an <code>AttributeError</code> exception. An easy way to do this is to create a <code>property</code> and only set the <code>fget</code> function. Instead of using the descriptor in Listing 4, we can construct a read-only attribute as follows:</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">def </span><span class="hl-identifier">__get_value</span><span class="hl-brackets">(</span><span class="hl-identifier">self</span><span class="hl-brackets">)</span><span class="hl-default">:
    </span><span class="hl-reserved">return </span><span class="hl-identifier">self</span><span class="hl-default">.</span><span class="hl-identifier">_value
my_value</span><span class="hl-default"> = </span><span class="hl-builtin">property</span><span class="hl-brackets">(</span><span class="hl-identifier">__get_value</span><span class="hl-brackets">)</span></pre></div></div>
<h2>Conclusion</h2>
<p>I hope that after reading this article you can see how powerful descriptors (especially data-descriptors) can be. Once you get the hang of them, they are a great way to implement &#8220;getters and setters&#8221; and read-only attributes. Data-Descriptors are also very useful for performing validation during the assignment operation, i.e. ensuring that a value remains a specific type, or in a specific form.</p>
<p>The more you play with descriptors and use them in your code, the more you&#8217;ll see how sophisticated and useful they can be. That being said, it&#8217;s important to remember that unless you have a good reason to use descriptors you probably don&#8217;t need them. There&#8217;s no need to sacrifice the readability of your code or the dynamism of Python just for the sake of using descriptors. But when you have a real reason for managed attributes, you&#8217;ll find that descriptors are more than up to the task.</p>
<p>[1] <a href="http://docs.python.org/ref/descriptor-invocation.html">http://docs.python.org/ref/descriptor-invocation.html</a><br />
[2] <a href="http://www.python.org/download/releases/2.2/descrintro/#property">http://www.python.org/download/releases/2.2/descrintro/#property</a><br />
[3] <a href="http://docs.python.org/ref/descriptor-invocation.html">http://docs.python.org/ref/descriptor-invocation.html</a><br />
[4] <a href="http://docs.python.org/ref/descriptors.html">http://docs.python.org/ref/descriptors.html</a><br />
[5] <a href="http://docs.python.org/ref/descriptors.html">http://docs.python.org/ref/descriptors.html</a><br />
[6] <a href="http://docs.python.org/ref/descriptors.html">http://docs.python.org/ref/descriptors.html</a><br />
[7] <a href="http://www.python.org/download/releases/2.2/descrintro/#property">http://www.python.org/download/releases/2.2/descrintro/#property</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.learningpython.com/2010/04/25/introducing-descriptors-and-properties/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

