<?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>Alice and Bob in Cryptoland &#187; Programming</title>
	<atom:link href="http://alicebob.cryptoland.net/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://alicebob.cryptoland.net</link>
	<description></description>
	<lastBuildDate>Mon, 14 Feb 2011 13:29:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>The C language still surprises me</title>
		<link>http://alicebob.cryptoland.net/the-c-language-still-surprises-me/</link>
		<comments>http://alicebob.cryptoland.net/the-c-language-still-surprises-me/#comments</comments>
		<pubDate>Sun, 10 Oct 2010 02:49:29 +0000</pubDate>
		<dc:creator>Conrado</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[book]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[gotcha]]></category>

		<guid isPermaLink="false">http://alicebob.cryptoland.net/?p=227</guid>
		<description><![CDATA[What does this code print? 1 2 3 4 5 6 7 8 9 10 11 12 #include &#60;stdio.h&#62; &#160; int main&#40;&#41; &#123; signed char x = -128; &#160; if &#40;x &#60; 0&#41; &#123; x = -x; &#125; printf&#40;&#34;x = %d\n&#34;, &#40;int&#41; x&#41;; return 0; &#125; I&#8217;ve been reading Matters Computational, an excellent (free) book [...]]]></description>
			<content:encoded><![CDATA[<p>What does this code print?</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">signed</span> <span style="color: #993333;">char</span> x <span style="color: #339933;">=</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">128</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>x <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        x <span style="color: #339933;">=</span> <span style="color: #339933;">-</span>x<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;x = %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span> x<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>I&#8217;ve been reading <a href="http://www.jjj.de/fxt/">Matters Computational</a>, an excellent (free) book by Jörg Arndt about programming and algorithms. It surprised me in the very first pages with this pitfall in two&#8217;s complement &#8211; there is always a number that is equal to its own negative, besides zero. The code above prints −128!</p>
<p>In hindsight, it&#8217;s pretty obvious. A <code>signed char</code> can hold values from −128 to 127 &#8212; that is, there are 127 positive numbers and 128 negative numbers! Therefore, it&#8217;s impossible to the unary negative operator to be one-to-one. The smallest negative number will always be mapped to itself. Of course, this also applies to <code>int</code>, etc.</p>
<p>The main implication of this fact is that, after the innocent-looking code</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>x <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> x <span style="color: #339933;">=</span> <span style="color: #339933;">-</span>x<span style="color: #339933;">;</span></pre></div></div>

<p>x is not guaranteed to be positive!</p>
]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/the-c-language-still-surprises-me/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The black magic of GDI+</title>
		<link>http://alicebob.cryptoland.net/the-black-magic-of-gdi/</link>
		<comments>http://alicebob.cryptoland.net/the-black-magic-of-gdi/#comments</comments>
		<pubDate>Sun, 07 Jun 2009 06:52:16 +0000</pubDate>
		<dc:creator>Conrado</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[cairo]]></category>
		<category><![CDATA[freeimage]]></category>
		<category><![CDATA[gdi]]></category>
		<category><![CDATA[pil]]></category>
		<category><![CDATA[quivi]]></category>

		<guid isPermaLink="false">http://alicebob.cryptoland.net/?p=188</guid>
		<description><![CDATA[One of the things I am most ashamed of on Quivi is its speed when opening large images (which are not uncommon nowadays, specially with digital photos). It&#8217;s embarrassing that the lame Windows Picture and Fax Viewer is lightning fast when opening those images! I&#8217;ve always wondered how the Viewer did that. I&#8217;ve searched about [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things I am most ashamed of on <a href="http://quivi.sourceforge.net/">Quivi</a> is its speed when opening large images (which are not uncommon nowadays, specially with digital photos). It&#8217;s embarrassing that the lame Windows Picture and Fax Viewer is lightning fast when opening those images!</p>
<p>I&#8217;ve always wondered how the Viewer did that. I&#8217;ve searched about it in the past but could never find anything about it. Then one of these days I was browsing the <a href="http://en.wikipedia.org/wiki/Windows_Picture_and_Fax_Viewer">Wikipedia page about the Viewer</a> and there I learned that it uses <a href="http://en.wikipedia.org/wiki/GDI%2B#GDI.2B">GDI+</a>.</p>
<p>GDI+ is a C++ library, but it is built upon <a href="http://msdn.microsoft.com/en-us/library/ms533969(VS.85).aspx">a flat C API</a> which I could easily use in Python via <a href="http://docs.python.org/library/ctypes.html">ctypes</a>. Long story short, I was able to modify Quivi to add support for viewing images with GDI+. And the result was amazing!</p>
<p>What about Linux? Well, something &#8220;equivalent&#8221; to GDI+ would be <a href="http://cairographics.org/">Cairo</a>, so I did some tests with it too (luckily, support for it was included in wxPython recently).</p>
<p>Here are the results for the time to load a huge 5704px x 5659px PNG image and rescale it to 1/20 of its size:</p>
<table class="booktabs">
<caption>Time to load and scale a PNG image</caption>
<thead>
<tr>
<th>Library</th>
<th>Time (s)</th>
</tr>
</thead>
<tbody>
<tr>
<td>FreeImage</td>
<td class="table-number">10.38</td>
</tr>
<tr>
<td>PIL</td>
<td class="table-number">9.90</td>
</tr>
<tr>
<td>GDI+</td>
<td class="table-number">2.22</td>
</tr>
<tr>
<td>Cairo (from FreeImage)</td>
<td class="table-number">3.60</td>
</tr>
<tr>
<td>Cairo (direct)</td>
<td class="table-number">3.28</td>
</tr>
</tbody>
</table>
<p>The reason for the two Cairo timings is that it supports reading directly from a PNG file but for e.g. JPG files you need to read the image with another library and to the format Cairo uses. I&#8217;ve used FreeImage to load the image and converted it to a Cairo surface.</p>
<p>Here are the results for the time to load and scaling the same image, but as a JPG:</p>
<table class="booktabs">
<caption>Time to load and scale a JPG image</caption>
<thead>
<tr>
<th>Library</th>
<th>Time (s)</th>
</tr>
</thead>
<tbody>
<tr>
<td>FreeImage</td>
<td class="table-number">6.91</td>
</tr>
<tr>
<td>PIL</td>
<td class="table-number">8.38</td>
</tr>
<tr>
<td>GDI+</td>
<td class="table-number">0.19</td>
</tr>
<tr>
<td>Cairo (from FreeImage)</td>
<td class="table-number">1.43</td>
</tr>
</tbody>
</table>
<p>Scary! How does GDI+ manages to do that? According to <a href="http://en.wikipedia.org/wiki/GDI%2B#GDI.2B">Wikipedia</a> it uses hardware acceleration&#8230; Cairo doesn&#8217;t lag begind considering that the scaling only takes 0.015 (!) but I did notice that even its best quality scaling isn&#8217;t so good in comparison to the others, which is kinda odd.</p>
<p>Anyway, I&#8217;ll try to release a new version of Quivi with GDI+ and Cairo support soon. Stay tuned.</p>
]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/the-black-magic-of-gdi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Yet another silly Python vs Java comparison</title>
		<link>http://alicebob.cryptoland.net/yet-another-silly-python-vs-java-comparison/</link>
		<comments>http://alicebob.cryptoland.net/yet-another-silly-python-vs-java-comparison/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 19:19:27 +0000</pubDate>
		<dc:creator>Conrado</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://alicebob.cryptoland.net/?p=172</guid>
		<description><![CDATA[I&#8217;ve been hacking the mspsim (a simulator) source to add support for a couple of stuffs in its profiler. At a certain point I had a hash table mapping functions to how many times they were called, and I had to sort them by that number of times. How to do that? List&#60;entry&#62; list = [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been hacking the mspsim (a simulator) source to add support for a couple of stuffs in its profiler. At a certain point I had a hash table mapping functions to how many times they were called, and I had to sort them by that number of times. How to do that?</p>
<pre>
List&lt;entry&gt; list = new LinkedList&lt;entry&gt;(callers.entrySet());
Collections.sort(list, new Comparator&lt;entry&gt;() {
    @Override
    public int compare(Entry o1, Entry o2) {
      return o2.getValue().compareTo(o1.getValue());
    }
});
</pre>
<p>And if it were Python:</p>
<pre>
lst = sorted(((n, fn) for fn, n in callers.iteritems()), reverse=True)
</pre>
<p>Yep, Java can be a pain.</p>
<p>Of course it&#8217;s not that simple, though. I&#8217;ve tested another simulator in Python and its code is very nice and readable and warm and fuzzy&#8230;</p>
<p>&#8230;but it&#8217;s 30 times slower than the Java one.</p>
]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/yet-another-silly-python-vs-java-comparison/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sandbox WordPress theme for 2.7 with threaded comments</title>
		<link>http://alicebob.cryptoland.net/sandbox-wordpress-theme-for-27-with-threaded-comments/</link>
		<comments>http://alicebob.cryptoland.net/sandbox-wordpress-theme-for-27-with-threaded-comments/#comments</comments>
		<pubDate>Sat, 14 Mar 2009 05:03:20 +0000</pubDate>
		<dc:creator>Conrado</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[sandbox]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://alicebob.cryptoland.net/?p=167</guid>
		<description><![CDATA[The Sandbox WordPress theme is a nice bare bones theme which can be easily used as a base to your own themes (preferably with a style.css file only, following the zen). The only problem is that its development is kinda frozen and it does not support new WordPress 2.7 features like threaded and paged comments. [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.plaintxt.org/themes/sandbox/">Sandbox</a> WordPress theme is a nice bare bones theme which can be easily used as a base to your own themes (preferably with a style.css file only, following the <a href="http://www.csszengarden.com/">zen</a>). The only problem is that its development is kinda frozen and it does not support new WordPress 2.7 features like threaded and paged comments.</p>
<p>There are already <a href="http://forums.sndbx.org/viewtopic.php?id=89">some hacks</a> to support them but I decided to take another approach. Since the comment loop was changed drastically, those hacks had to&#8230; well, hack away in order to keep backward compatibility with Sandbox-based themes. Instead, I decided to embrace the new comment loop in WP (which is simple and doesn&#8217;t allow much customization without resorting to the hackish callback, but it generates code very close to what Sandbox does).</p>
<p>If you like the idea, feel free to <strong><a href="http://alicebob.cryptoland.net/files/sandbox-27-tweaks.zip">download my customization</a></strong> (just overwrite the comments.php and header.php in Sandbox). You&#8217;ll probably have to tweak your previous themes a little, though.</p>
<p>Tip: if you want do get rid of the &#8220;says:&#8221; in the comments (e.g. &#8220;Alice says:&#8221;), put this in your stylesheet:</p>
<pre>
.says { display: none; }
</pre>
<p>If you want to change the avatar size, change the following line in comments.php</p>
<pre>
</pre>
<p>to</p>
<pre>
</pre>
<p>(change 40 to whichever size you want)</p>
<p>&#8230;and I&#8217;ve not activated it in this blog for now, since it barely gets comments. Sorry, no live preview <img src='http://alicebob.cryptoland.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/sandbox-wordpress-theme-for-27-with-threaded-comments/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Access violation errors with callbacks in ctypes</title>
		<link>http://alicebob.cryptoland.net/access-violation-errors-with-callbacks-in-ctypes/</link>
		<comments>http://alicebob.cryptoland.net/access-violation-errors-with-callbacks-in-ctypes/#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 [...]]]></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" 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>, <span style="color: #ff4500;">0</span><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" 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>, <span style="color: #ff4500;">0</span><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/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Why I rewrote Quivi from scratch</title>
		<link>http://alicebob.cryptoland.net/why-i-rewrote-quivi-from-scratch/</link>
		<comments>http://alicebob.cryptoland.net/why-i-rewrote-quivi-from-scratch/#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 [...]]]></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 &#8211; 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/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python, Phyton&#8230; Pytohn?</title>
		<link>http://alicebob.cryptoland.net/python-phyton-pytohn/</link>
		<comments>http://alicebob.cryptoland.net/python-phyton-pytohn/#comments</comments>
		<pubDate>Fri, 15 Aug 2008 15:02:15 +0000</pubDate>
		<dc:creator>Conrado</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://alicebob.cryptoland.net/?p=24</guid>
		<description><![CDATA[Essa é nova: As primeiras versões para Java e Pytohn já estão disponíveis para download a partir do serviço Google Code. Não dá para entender a inabilidade geral das pessoas de escreverem &#8220;Python&#8221; direito.]]></description>
			<content:encoded><![CDATA[<p>Essa é <a href="http://exameinformatica.clix.pt/noticias/software/998026.html">nova</a>:</p>
<blockquote><p>As primeiras versões para Java e <strong>Pytohn</strong> já estão disponíveis para download a partir do serviço Google Code. </p></blockquote>
<p>Não dá para entender a inabilidade geral das pessoas de escreverem &#8220;Python&#8221; direito.</p>
]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/python-phyton-pytohn/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Closure gotcha (with Python)</title>
		<link>http://alicebob.cryptoland.net/closure-gotcha-with-python/</link>
		<comments>http://alicebob.cryptoland.net/closure-gotcha-with-python/#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(n): def number_printer(): print n return number_printer printer = make_number_printer(5) printer() The function make_number_printer receives a number and returns a function which, when called, prints that same number. It&#8217;s not [...]]]></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>
<pre>def make_number_printer(n):
    def number_printer():
        print n
    return number_printer

printer = make_number_printer(5)
printer()</pre>
<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>
<pre>printer_lst = []
for i in xrange(10):
    def number_printer():
        print i
    printer_lst.append(number_printer)

for printer in printer_lst:
    printer()</pre>
<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>
<pre>def make_number_printer(n):
    def number_printer():
        print n
    return number_printer

printer_lst = []
for i in xrange(10):
    printer_lst.append(make_number_printer(i))

for printer in printer_lst:
    printer()</pre>
<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>
<pre>printer_lst = []
for i in xrange(10):
    def number_printer(x=i):
        print x
    printer_lst.append(number_printer)

for printer in printer_lst:
    printer()</pre>
<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>
<pre>class Button:
    #This is a dummy Button class; suppose
    #it's part of a GUI library and for some reason
    #you can't subclass it

    def __init__(self):
        self.listener = None

    def set_click_listener(self, fn):
        self.listener = fn

    def on_click(self):
        self.listener()

#Create 10 buttons...
buttons = [Button() for i in xrange(10)]
#And suppose the buttons are added to the GUI after

#Set the listeners to the click event.
#The number of buttons may change in the future
#and all of them have the same code, the
#only difference is the button index. So it's better
#to do this within a loop.
for i in xrange(10):
    def on_click():
        #Suppose there is something more useful here
        print i
    buttons[i].set_click_listener(on_click)

#Simulate a click in each button
for j in xrange(10):
    buttons[j].on_click()</pre>
]]></content:encoded>
			<wfw:commentRss>http://alicebob.cryptoland.net/closure-gotcha-with-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

