<?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/"
	>

<channel>
	<title>Alice and Bob in Cryptoland</title>
	<atom:link href="http://alicebob.cryptoland.net/feed/en/" rel="self" type="application/rss+xml" />
	<link>http://alicebob.cryptoland.net</link>
	<description></description>
	<pubDate>Wed, 17 Dec 2008 01:30:25 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Visualizing group structure with colored addition/multiplication tables</title>
		<link>http://alicebob.cryptoland.net/visualizing-group-structure-with-colored-additionmultiplication-tables/en/</link>
		<comments>http://alicebob.cryptoland.net/visualizing-group-structure-with-colored-additionmultiplication-tables/en/#comments</comments>
		<pubDate>Sun, 07 Dec 2008 04:32:51 +0000</pubDate>
		<dc:creator>Conrado</dc:creator>
		
		<category><![CDATA[Cryptography]]></category>

		<category><![CDATA[Math]]></category>

		<category><![CDATA[elliptic curve]]></category>

		<category><![CDATA[field]]></category>

		<category><![CDATA[group]]></category>

		<category><![CDATA[RSA]]></category>

		<category><![CDATA[visualization]]></category>

		<guid isPermaLink="false">http://alicebob.cryptoland.net/?p=70</guid>
		<description><![CDATA[When working with finite fields, if the number of elements is a prime power  with m > 1, you can represent the elements as polynomials with degree m-1 and do the field addition and multiplication modulo a irreducible polynomial with degree m.
The field GF(5) is composed by the numbers 0 to 4. We don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>When working with finite fields, if the number of elements is a prime power <img src='/wp-content/plugins/latexrender/pictures/3cb905ad7f180e0e504be78f938286c0_2.94444pt.png' title='p^m' alt='p^m'  style="vertical-align:-2.94444pt;" > with m > 1, you can represent the elements as polynomials with degree m-1 and do the field addition and multiplication modulo a irreducible polynomial with degree m.</p>
<p>The field GF(5) is composed by the numbers 0 to 4. We don&#8217;t need to represent its elements as polynomials since m=1. Addition is done modulo 5 and multiplication also modulo 5. So 2 + 3 = 0; 4 * 2 = 3; and so on. This is the addition table for GF(5):</p>
<p class="aligncenter">
<a href="http://alicebob.cryptoland.net/wp-content/uploads/z5m.png"><img src="http://alicebob.cryptoland.net/wp-content/uploads/z5m.png" alt="Multiplicative table of integers modulo 5" title="Z5*" width="100" height="100" class="size-full wp-image-74" /></a></p>
<p>The rows, top down, represent 0 to 4. The columns, right to left, represent 0 to 4. Each square is the result of the addition of the respective numbers in the row / column it belongs to. Black is 0, purple is 1, red is 2, orange is 3, yellow is 4.</p>
<p>In the field GF(25) = GF(5²), as I said, you represent each element as a polynomial. So we have 25 elements: 0 to 4; x, x+ 1, &#8230;, x + 4; 2x, 2x + 1, &#8230;; 3x, 3x + 1, &#8230;; 4x, 4x + 1, &#8230;, 4x + 4.</p>
<p>In order to add two elements, add them as you would add two polynomials, but remember that the coefficients are in GF(5); for example, in GF(5²), we have (3x + 2) + (4x + 4) = (2x + 1). In order to multiply two elements, multiply them as usual but then take the result modulo an irreducible polynomial. So, with GF(5²) modulo <img src='/wp-content/plugins/latexrender/pictures/c8245f08bfc46ce263ee1b56a53c4bb3_1.83333pt.png' title='x^2 + 4x + 2' alt='x^2 + 4x + 2'  style="vertical-align:-1.83333pt;" >, you have (2x + 5) * (3x + 4) = (4x + 3).</p>
<p>I always wondered what would happen when you changed the modulus. Obviously the group &#8220;changes&#8221;, but in order to actually see it, I&#8217;ve built the multiplication table for GF(5²) modulus <img src='/wp-content/plugins/latexrender/pictures/c8245f08bfc46ce263ee1b56a53c4bb3_1.83333pt.png' title='x^2 + 4x + 2' alt='x^2 + 4x + 2'  style="vertical-align:-1.83333pt;" > and <img src='/wp-content/plugins/latexrender/pictures/94597cfc22fd599167566ac291cab706_1.83333pt.png' title='x^2 + 3x + 3' alt='x^2 + 3x + 3'  style="vertical-align:-1.83333pt;" >:</p>
<p class="aligncenter">
<img src="http://alicebob.cryptoland.net/wp-content/uploads/gf25m_x2_4x_2.png" alt="Multiplicative table for GF(5^2)/(x^2+4x+2)" title="gf25m_x2_4x_2" width="200" height="200" class="size-medium wp-image-76" /><img src="http://alicebob.cryptoland.net/wp-content/uploads/gf25m_x2_3x_3.png" alt="Multiplicative table for GF(5^2)/(x^2+3x+3)" title="gf25m_x2_3x_3" width="200" height="200" class="size-medium wp-image-85" />
</p>
<p>Yep, they&#8217;re different :D</p>
<p>Of course, both are isomorphic, so you&#8217;re free to pick your favorite modulus.</p>
<h3>Multiplicative group of integers modulo n vs group of points in a elliptic curve</h3>
<p>Then I got curious: how would the multiplication table of integers modulo n look like? This group is the group used in many cryptographic schemes, like RSA. This is the multiplication table for integers modulo 509:</p>
<p class="aligncenter">
<img src="http://alicebob.cryptoland.net/wp-content/uploads/z509m.png" alt="Multiplicative table for integers modulo 509" title="z509m" width="508" height="508" class="size-full wp-image-78" />
</p>
<p>Pretty (and trippy)!</p>
<p>What about the group of points on a elliptic curve over a finite field, which is also a group used in cryptographic schemes? This is the additive table for the points on <img src='/wp-content/plugins/latexrender/pictures/063f0022cf45f07999ad1e5dc98fb929_2.94444pt.png' title='y^2 = x^3 + 4x + 1' alt='y^2 = x^3 + 4x + 1'  style="vertical-align:-2.94444pt;" > over GF(503):</p>
<p class="aligncenter">
<img src="http://alicebob.cryptoland.net/wp-content/uploads/e_4_1_503.png" alt="Additive table for points in y^2 = x^3 +4x + 1 over GF(503)" title="e_4_1_503" width="516" height="516" class="size-full wp-image-79" />
</p>
<p>The difference between them is striking; the elliptic group seems almost random. This is (intuitively speaking! I’m not being formal here) the reason why this group is used in cryptography in the first place: since the group structure is more “messed up”, you can get away with using groups of much smaller size (no smaller than <img src='/wp-content/plugins/latexrender/pictures/67152a8192fb54b178bfeeb27bc6dba4_1.0pt.png' title='2^{160}' alt='2^{160}'  style="vertical-align:-1.0pt;" > elements) than with multiplicative groups of integers modulo n (no smaller than <img src='/wp-content/plugins/latexrender/pictures/b93d5f7e3e3169edf86352ab5c5ca870_1.0pt.png' title='2^{1024}' alt='2^{1024}'  style="vertical-align:-1.0pt;" > elements). This is not set in stone though; maybe someday someone will come up with a better method to crack this seemingly random structure (for now the best method to solve the discrete log problem for elliptic groups is exponential, while the best method for integers modulo n is sub-exponential).</p>
<p>It’s worth mentioning that even this elliptic group is not that extraordinary: it is isomorphic to the very simple additive group of integers modulo 506:</p>
<p class="aligncenter"><img src="http://alicebob.cryptoland.net/wp-content/uploads/z506a.png" alt="Additive table of integers modulo 516" title="z506a" width="506" height="506" class="size-full wp-image-89" />
</p>
<p>The big problem is to find the isomorphism! You can see this better with a small example. This is the elliptic group of <img src='/wp-content/plugins/latexrender/pictures/b6aba1809da2ca055b98749a6fd0e808_2.94444pt.png' title='y^2 = x^3 + 3x + 2' alt='y^2 = x^3 + 3x + 2'  style="vertical-align:-2.94444pt;" > over GF(5) (left) which is isomorphic to the additive group modulo 5 (right):</p>
<p class="aligncenter">
<img src="http://alicebob.cryptoland.net/wp-content/uploads/e_3_2_5.png" alt="Additive table of points on y^2 = x^3 + 3x + 2 over GF(5)" title="e_3_2_5" width="100" height="100" class="size-full wp-image-81" /><img src="http://alicebob.cryptoland.net/wp-content/uploads/z5a.png" alt="Additive table for integers modulo 5" title="z5a" width="100" height="100" class="size-full wp-image-83" />
</p>
<p>(OK, it&#8217;s not that easy to see)</p>
<h3>Software</h3>
<p>To generate those images, I&#8217;ve used Python with <a href="http://www.pythonware.com/products/pil/">PIL</a> and <a href="http://www.sagemath.org/">Sage</a>. Sage aims to be a open source replacement for (expensive) software like Magma, Maple, Mathematica and Matlab. Since I&#8217;ve never used those, I can&#8217;t really say how it is going in its mission, but it&#8217;s really awesome. If you&#8217;re a Windows user you&#8217;ll probably be scared by the fact that the Windows version of Sage is actually an entire Linux virtual machine! They&#8217;re working to port it natively, but even until then, it&#8217;s worth it (and you&#8217;ll have an excuse to try Linux ;) )</p>
<h3>Update</h3>
<p>Someone asked for the source code used to generate those. It&#8217;s ugly (I&#8217;ve added comments at least) but you can download it here: the <a href="http://alicebob.cryptoland.net/wp-content/uploads/gentable.sage">sage script</a> and the <a href="http://alicebob.cryptoland.net/wp-content/uploads/plottable.py">python script</a>. In the sage script, uncomment the lines representing what you want to plot, then run <code>./sage gentable.sage</code> (or whichever path to were sage is). It will generate a data.txt in the same folder. Now run <code>python plottable.py img.png</code> to plot it on the img.png file (or omit it to show on the screen). You&#8217;ll need to have PIL installed.</p>
<p>If you don&#8217;t want to plot fancy stuff as elliptic groups, you can easily transform the gentable.sage into a normal Python script and write the addition/multiplication yourself (like a + b % n). Have fun, and feel free to ask anything.</p>
]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/visualizing-group-structure-with-colored-additionmultiplication-tables/feed/en/</wfw:commentRss>
		</item>
		<item>
		<title>Access violation errors with callbacks in ctypes</title>
		<link>http://alicebob.cryptoland.net/access-violation-errors-with-callbacks-in-ctypes/en/</link>
		<comments>http://alicebob.cryptoland.net/access-violation-errors-with-callbacks-in-ctypes/en/#comments</comments>
		<pubDate>Sat, 11 Oct 2008 17:19:15 +0000</pubDate>
		<dc:creator>Conrado</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[ctypes]]></category>

		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://alicebob.cryptoland.net/?p=49</guid>
		<description><![CDATA[I&#8217;ve just spent a few hours trying to solve this bug, so I&#8217;m publishing this so maybe it will help someone with this issue&#8230;
Assume that you&#8217;re working with a DLL/.so library through ctypes in Python, and this library allows you to set a callback for some other function. In my case, I was working with [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just spent a few hours trying to solve this bug, so I&#8217;m publishing this so maybe it will help someone with this issue&#8230;</p>
<p>Assume that you&#8217;re working with a DLL/.so library through ctypes in Python, and this library allows you to set a callback for some other function. In my case, I was working with unrar.dll. The code was something among these lines:</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;">UNRARCALLBACK = ctypes.<span style="color: black;">WINFUNCTYPE</span><span style="color: black;">&#40;</span>ctypes.<span style="color: black;">c_int</span>, ctypes.<span style="color: black;">c_uint</span>, ctypes.<span style="color: black;">c_long</span>, ctypes.<span style="color: black;">c_long</span>, ctypes.<span style="color: black;">c_long</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#in a class...</span>
RARSetCallback<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">handle</span>, UNRARCALLBACK<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">callback_fn</span><span style="color: black;">&#41;</span>, 0<span style="color: black;">&#41;</span>
RARProcessFile<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">handle</span>, RAR_TEST, <span style="color: #008000;">None</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The first lines constructs the function prototype, the second sets the callback in a function of the DLL file, and the third calls a function in the DLL which will call the callback.</p>
<p>Can you spot the error?</p>
<p>The code worked fine in Python 2.5, but then I changed to 2.6 and it stopped working. I got a &#8220;WindowsError: exception: access violation reading&#8230;&#8221; (or writing) exception in the third call.</p>
<p>The reason, which is obvious in hindsight, is cleared explained in the docs:</p>
<blockquote><p>
Make sure you keep references to CFUNCTYPE objects as long as they are used from C code. ctypes doesn’t, and if you don’t, they may be garbage collected, crashing your program when a callback is made.
</p></blockquote>
<p>(Though it&#8217;s not explicit, it applies to WINFUNCTYPE objects too)</p>
<p>The WINFUNCTYPE object created in the second line no longer exists in the third line, so when the callback was called, it no longer pointed to a valid address. The solution is simple &mdash; just keep a reference to the object:</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;">UNRARCALLBACK = ctypes.<span style="color: black;">WINFUNCTYPE</span><span style="color: black;">&#40;</span>ctypes.<span style="color: black;">c_int</span>, ctypes.<span style="color: black;">c_uint</span>, ctypes.<span style="color: black;">c_long</span>, ctypes.<span style="color: black;">c_long</span>, ctypes.<span style="color: black;">c_long</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#inside a class...</span>
<span style="color: #008000;">self</span>.<span style="color: black;">callback_ref</span> = UNRARCALLBACK<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">callback_fn</span><span style="color: black;">&#41;</span>
RARSetCallback<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">rarFile</span>.<span style="color: black;">RAR</span>._handle, <span style="color: #008000;">self</span>.<span style="color: black;">callback_ref</span>, 0<span style="color: black;">&#41;</span>
RARProcessFile<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">rarFile</span>.<span style="color: black;">RAR</span>._handle, RAR_TEST, <span style="color: #008000;">None</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The only mystery left is why the old code worked on 2.5!</p>
]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/access-violation-errors-with-callbacks-in-ctypes/feed/en/</wfw:commentRss>
		</item>
		<item>
		<title>Quivi 1.0 released</title>
		<link>http://alicebob.cryptoland.net/quivi-10-released/en/</link>
		<comments>http://alicebob.cryptoland.net/quivi-10-released/en/#comments</comments>
		<pubDate>Mon, 22 Sep 2008 01:40:09 +0000</pubDate>
		<dc:creator>Conrado</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<category><![CDATA[quivi]]></category>

		<guid isPermaLink="false">http://alicebob.cryptoland.net/?p=43</guid>
		<description><![CDATA[I&#8217;ve just released the new version of my image viewer and manga / comic reader, Quivi (only for Windows right now, but it will be ported to Linux and maybe to Mac). I&#8217;ve rewritten it from scratch, check my last post for more info.
The new features added were:

Prefetching of the next image
Wallpaper dialog
Start directory option

But [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just released the new version of my image viewer and manga / comic reader, <a href="http://quivi.sourceforge.net/">Quivi</a> (only for Windows right now, but it will be ported to Linux and maybe to Mac). I&#8217;ve rewritten it from scratch, check my <a href="http://alicebob.cryptoland.net/why-i-rewrote-quivi-from-scratch/en/">last post</a> for more info.</p>
<p>The new features added were:</p>
<ul>
<li>Prefetching of the next image</li>
<li>Wallpaper dialog</li>
<li>Start directory option</li>
</ul>
<p>But that is only the beginning; now it will be much more easy for me to work on Quivi.</p>
<p>There are many comic readers around; like <a href="http://www.geocities.com/davidayton/CDisplay">CDisplay</a> (outdated, but very popular), <a href="http://comical.sourceforge.net/">Comical</a> and <a href="http://comix.sourceforge.net/">Comix</a>. They have much more features than Quivi, and I must admit that I often thought on giving up on Quivi. But I just couldn&#8217;t.</p>
<p>I wrote it mainly for myself; when I started there was only CDisplay. The first version was written with Visual Basic (go on, laugh). Then I changed to C++. And now I changed to Python, and I hope this is the last language change :) It&#8217;s a hobby project that I grew to love. It suits my needs, but I&#8217;d really like to suit the needs of other people too! </p>
<p>It is scary when you realize that people are using your software. I feel responsible; wherever I find someone <a href="http://hirvine.com/blog/1546/quivi-manga-reading-tool/">criticizing it</a>, I feel guilty for not attending those people needs. Yes, that&#8217;s stupid, but it&#8217;s how I am. At the same time, though, it&#8217;s awesome to know that there are people who like it and find it useful.</p>
<p>If you have <strong>any</strong> suggestion, comment, complain about Quivi, please send it to me!</p>
]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/quivi-10-released/feed/en/</wfw:commentRss>
		</item>
		<item>
		<title>Why I rewrote Quivi from scratch</title>
		<link>http://alicebob.cryptoland.net/why-i-rewrote-quivi-from-scratch/en/</link>
		<comments>http://alicebob.cryptoland.net/why-i-rewrote-quivi-from-scratch/en/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 02:31:39 +0000</pubDate>
		<dc:creator>Conrado</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Software]]></category>

		<category><![CDATA[c]]></category>

		<category><![CDATA[python]]></category>

		<category><![CDATA[quivi]]></category>

		<category><![CDATA[wxpython]]></category>

		<guid isPermaLink="false">http://alicebob.cryptoland.net/?p=35</guid>
		<description><![CDATA[Joel Spolsky, popular software engineering, said in this blog:
(&#8230;) They [Netscape] did it by making the single worst strategic mistake that any software company can make:
They decided to rewrite the code from scratch.
I agree, mostly. Many projects market that they&#8217;ve been &#8220;rewritten from scratch&#8221; as if it was something marvelous, and most of time, it&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Joel Spolsky, popular software engineering, <a href="http://www.joelonsoftware.com/articles/fog0000000069.html">said</a> in this <a href="http://www.joelonsoftware.com/">blog</a>:</p>
<blockquote><p>(&#8230;) They [Netscape] did it by making the single worst strategic mistake that any software company can make:</p>
<p>They decided to rewrite the code from scratch.</p></blockquote>
<p>I agree, mostly. Many projects market that they&#8217;ve been &#8220;rewritten from scratch&#8221; as if it was something marvelous, and most of time, it&#8217;s just a sign that the new version probably has more bugs than the previous. But, wait, I just rewrote <a href="http://quivi.sourceforge.net/">Quivi</a> (a image viewer and comic / manga reader) from scratch! Well, why?</p>
<p>Well, I thought I really had to justify this. So here are the reasons:</p>
<ul>
<li>It is a small project. Rewriting it certainly isn&#8217;t as hard as rewriting a browser!</li>
<li>I couldn&#8217;t stand C++ anymore (the programming language I used before). Of course, this isn&#8217;t C++ fault <em>per se</em>. It has its uses &mdash; the right tool for the right job, and so on. But to write an desktop application? It&#8217;s overkill. If you manage to pull it of, hey, kudos to you. But I had no motivation to work on it anymore.</li>
<li>I love Python (the programming language I use now), and of course, I&#8217;m <a href="http://xkcd.com/353/">not the only one</a>. Programming is <strong>fun</strong> in Python, so much that had the motivation to rewrite Quivi from scratch in the first place! And of course, it will be much more easier for me to keep working on Quivi.</li>
<li>I could change GUI libraries. <a href="http://smartwin.sourceforge.net/">SmartWin</a> is a nice library, and uses templates in very interesting ways; when programming Quivi I ended up involved with its development too. But it has its bugs, and <em>because</em> it uses templates extensively, it&#8217;s awful <strong>slow</strong> to compile an application that uses it. I&#8217;ve changed to <a href="http://wxpython.org/">wxPython</a>, which is a very mature GUI library - and cross platform to boot.</li>
</ul>
<p>Of course, there are some downsides with the change. The whole software package is much bigger due to the dependencies (the installer jumped from 900K to 5MB!). And the program is a little bit slower, mainly when starting up, and uses more memory (9MB to 30MB with no images loaded). But I think it was a good enough trade-off.</p>
<p>Rewriting from scratch must be considered carefully, and in this case, I think it was a good idea. Quivi is a hobby project, and I guess the main point of it is to have fun writing it, and to make users happy. I hope I can do both with this new version (which will be released soon).</p>
]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/why-i-rewrote-quivi-from-scratch/feed/en/</wfw:commentRss>
		</item>
		<item>
		<title>Closure gotcha (with Python)</title>
		<link>http://alicebob.cryptoland.net/closure-gotcha-with-python/en/</link>
		<comments>http://alicebob.cryptoland.net/closure-gotcha-with-python/en/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 18:34:25 +0000</pubDate>
		<dc:creator>Conrado</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[closure]]></category>

		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://alicebob.cryptoland.net/?p=15</guid>
		<description><![CDATA[Do you know what a closure is? Basically, it&#8217;s a function created at runtime that references variables defined in a outer scope. For example:

def make_number_printer&#40;n&#41;:
    def number_printer&#40;&#41;:
        print n
    return number_printer
&#160;
printer = make_number_printer&#40;5&#41;
printer&#40;&#41;

The function make_number_printer receives a number and returns a function [...]]]></description>
			<content:encoded><![CDATA[<p>Do you know what a closure is? Basically, it&#8217;s a function created at runtime that references variables defined in a outer scope. For example:</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> make_number_printer<span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> number_printer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> n
    <span style="color: #ff7700;font-weight:bold;">return</span> number_printer
&nbsp;
printer = make_number_printer<span style="color: black;">&#40;</span><span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
printer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The function <code>make_number_printer</code> receives a number and returns a function which, when called, prints that same number. It&#8217;s not the most useful function in the world, but it does show how closures work. In this case, the <code>number_printer</code> function is a closure, because it references the variable <code>n</code> which is in an outer scope (of the make_number_printer function).</p>
<p>My intention here, though, it&#8217;s not to explain what closures are but to show a property of them which may cause some confusion (and made me spent quite some time hunting for a bug caused by it). What does this code prints when run?</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;">printer_lst = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> number_printer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> i
    printer_lst.<span style="color: black;">append</span><span style="color: black;">&#40;</span>number_printer<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> printer <span style="color: #ff7700;font-weight:bold;">in</span> printer_lst:
    printer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>It loops between 0 and 10 creating a <code>number_printer</code> function and appending it to a list. Then it loops through the functions of the list, calling them. You would expect it to print the numbers 0 to 9, right?</p>
<p>Wrong! It prints the number 9 ten times.</p>
<p>The problem is that most people (including me, before learning this) think that closures work by evaluating the variables in the outer scope and storing their values to use when necessary. But actually they keep an <em>reference</em> to those variables, and if their contents change, the closure will use the new value. Since our variable <code>i</code> stores the value 9 after the closures are created, that is the value they will print. This happens even if the variable <code>i</code> goes out of scope after the closures are created (e.g., if the first <code>for</code> were inside a function).</p>
<p>So how to solve this? You can move the creation of the closure to another function, like this:</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> make_number_printer<span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> number_printer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> n
    <span style="color: #ff7700;font-weight:bold;">return</span> number_printer
&nbsp;
printer_lst = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>:
    printer_lst.<span style="color: black;">append</span><span style="color: black;">&#40;</span>make_number_printer<span style="color: black;">&#40;</span>i<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> printer <span style="color: #ff7700;font-weight:bold;">in</span> printer_lst:
    printer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Here the closure will reference the variable <code>n</code>, which has different instances for each different closure created. Another alternative is to use a somewhat <a href="http://effbot.org/zone/default-values.htm">contrived Python &#8220;feature&#8221;</a> which is the fact that default parameter values are evaluated when the function is defined and not when they are called:</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;">printer_lst = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> number_printer<span style="color: black;">&#40;</span>x=i<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> x
    printer_lst.<span style="color: black;">append</span><span style="color: black;">&#40;</span>number_printer<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> printer <span style="color: #ff7700;font-weight:bold;">in</span> printer_lst:
    printer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>When <code>def number_printer(x=i):</code> is run, the variable <code>i</code> is evaluated and its value is saved in the function definition; so, each time the function is defined (i.e., the closure is created), the current value of <code>i</code> is &#8220;frozen&#8221;.</p>
<p>If somebody is thinking, &#8220;but I&#8217;ll never run into this situation&#8221;, here is a little more real example (which actually happened to me when I was coding a Flash game, which uses ActionScript). Basically it&#8217;s the same code above and has the same issue:</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> Button:
    <span style="color: #808080; font-style: italic;">#This is a dummy Button class; suppose</span>
    <span style="color: #808080; font-style: italic;">#it's part of a GUI library and for some reason</span>
    <span style="color: #808080; font-style: italic;">#you can't subclass it</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">listener</span> = <span style="color: #008000;">None</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> set_click_listener<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, fn<span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">listener</span> = fn
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> on_click<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">listener</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#Create 10 buttons...</span>
buttons = <span style="color: black;">&#91;</span>Button<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
<span style="color: #808080; font-style: italic;">#And suppose the buttons are added to the GUI after</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#Set the listeners to the click event.</span>
<span style="color: #808080; font-style: italic;">#The number of buttons may change in the future</span>
<span style="color: #808080; font-style: italic;">#and all of them have the same code, the</span>
<span style="color: #808080; font-style: italic;">#only difference is the button index. So it's better</span>
<span style="color: #808080; font-style: italic;">#to do this within a loop. </span>
<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> on_click<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
        <span style="color: #808080; font-style: italic;">#Suppose there is something more useful here</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> i
    buttons<span style="color: black;">&#91;</span>i<span style="color: black;">&#93;</span>.<span style="color: black;">set_click_listener</span><span style="color: black;">&#40;</span>on_click<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#Simulate a click in each button</span>
<span style="color: #ff7700;font-weight:bold;">for</span> j <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>:
    buttons<span style="color: black;">&#91;</span>j<span style="color: black;">&#93;</span>.<span style="color: black;">on_click</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/closure-gotcha-with-python/feed/en/</wfw:commentRss>
		</item>
	</channel>
</rss>
