<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Stories For Sad Robots &#187; Programming</title>
	<atom:link href="http://erezsh.wordpress.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://erezsh.wordpress.com</link>
	<description>Programming, Design, Art and AI</description>
	<lastBuildDate>Sun, 21 Jun 2009 21:10:18 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='erezsh.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/49afd6a81a92fa8dbe020b8fca69e7f7?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Stories For Sad Robots &#187; Programming</title>
		<link>http://erezsh.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://erezsh.wordpress.com/osd.xml" title="Stories For Sad Robots" />
		<item>
		<title>Lazier Copy-On-Write</title>
		<link>http://erezsh.wordpress.com/2009/06/21/lazier-copy-on-write/</link>
		<comments>http://erezsh.wordpress.com/2009/06/21/lazier-copy-on-write/#comments</comments>
		<pubDate>Sun, 21 Jun 2009 18:13:10 +0000</pubDate>
		<dc:creator>erezsh</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[copy on write]]></category>
		<category><![CDATA[cow]]></category>
		<category><![CDATA[coward]]></category>
		<category><![CDATA[fragmentation]]></category>
		<category><![CDATA[lazy]]></category>

		<guid isPermaLink="false">http://erezsh.wordpress.com/?p=161</guid>
		<description><![CDATA[Copy-on-write (COW) is a popular mechanism of lazy evaluation, that helps improve running speed and reduce memory requirements by transparently delaying the copying of data. Essentially, this is how it works: When you try to copy an object, you are instead given a fake object. Attempts to read that new object will instead read from [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=161&subd=erezsh&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://en.wikipedia.org/wiki/Copy-on-write" target="_blank">Copy-on-write</a> (COW) is a popular mechanism of <a href="http://en.wikipedia.org/wiki/Lazy_evaluation" target="_blank">lazy evaluation</a>, that helps improve running speed and reduce memory requirements by transparently delaying the copying of data. Essentially, this is how it works: When you try to copy an object, you are instead given a fake object. Attempts to read that new object will instead read from the original object. Writing to the object will create a new copy (as originally requested) and refer to it in the future for reads and writes.</p>
<p>It allows to write simpler and safer programs. For instance, a programmer can pass &#8220;copies&#8221; of his data with minimal performance impact, and not have to worry about others changing his original data.</p>
<p>It&#8217;s great, but can it be more?</p>
<p>I present here two proposals for extending this idea for even greater optimization. They are far from my areas of expertise, so I hope they still make sense.</p>
<p><strong>1. Copy-On-Write + Fragmentation</strong></p>
<p style="direction:ltr;">Fragmentation of data is a mechanism that allows different parts (blocks) of data to reside in different locations in memory while appearing intact (that is, sequential).  This mechanism is often accused of  slowing the computer down. However, its a critical feature of <a href="http://en.wikipedia.org/wiki/Virtual_memory" target="_blank">virtual memory</a>, which is a basis to all modern operating systems.</p>
<p style="direction:ltr;">Introducing fragmentation into your data structures has many benefits, but let&#8217;s discuss the benefits regarding COW, which may be obvious by now: On write, you don&#8217;t have to copy all of the data, just the blocks which are being changed. This can be a big difference, if you&#8217;re changing a few bytes in a 50mb string.</p>
<p style="direction:ltr;">You still have to copy the meta-data (such as, where are the blocks, what is the next block, etc.), but that&#8217;s a small price to pay, and a reasonable design requirement.</p>
<p style="direction:ltr;">Now instead of copying the entire data, you copy only a fragment of it. How big is that fragment? Perhaps a fixed size, such as 64k. But assuming you have no real restriction on the size of these data blocks, the next logical step, in my eyes, is to ask: Why not make it as small as possible? That is, why not intentionally fragment the block into three smaller blocks: Before the area that is to be written, the area that is to be written, and after the area to be written. At this point we continue as we originally planned: We copy only the block which is to be written, which is, of course, exactly as small as it can be.</p>
<p style="direction:ltr;">Eventually, we have a model in which writing <em>n</em> bytes into a COWed data of <em>m</em> bytes takes <em>O(n) </em>time and memory, instead of the original <em>O(m+n) </em>time and <em>O(m)</em> memory. I argue that in the common case, <em>n</em> is significantly smaller than <em>m</em>, and so the win is big<em>.</em></p>
<p style="direction:ltr;">Of course, fragmentation has a habit of slowing down reading times. When fragmentation is &#8220;too high&#8221;, it is possible to defragment the memory (an occasional O(<em>m</em>) process). The optimal balance of fragmentation depends heavily on the frequency of reads vs of writes, but I argue that even a sub-optimal, common-case balance, will produce an improvement in performance.</p>
<p style="direction:ltr;">Edit: I&#8217;ve been unclear about how it affects look-ups. Fragmentation to blocks of fixed size remains O(1) for getting and setting items. However, for variable-size blocks it&#8217;s not so simple. A search tree can achieve a look-up of  O(log<em>n</em>) where <em>n</em> is number of fragments, which is a lot slower than the original array peformance. It is probably only a good idea if you have access to the operating system&#8217;s memory management, or if the use of look-ups is rare (and then an occasional defragmentation would still be necessary). Still, fixed-size fragments are <em>good enough</em>, and they can be dynamically resized with little cost, as long as the resize is uniform.</p>
<p style="direction:ltr;">
<p style="direction:ltr;"><strong>2. Copy-On-Write-And-ReaD</strong></p>
<p style="direction:ltr;">Or in short, COWARD, is a mechanism to even further delay copying, to only after the written data is also read. That is, when the programmer requests to write data, this mechanism will instead journal the data, producing sort of a &#8220;diff&#8221;. Only when the programmer attempts to read the result, the original data is copied and the diff is applied. A diff structure is provided by any implementation of lazy evaluation, by definition, but perhaps there are other more suitable diff structures for this purpose.</p>
<p style="direction:ltr;">This starts to make more sense with fragmentation: Then the diff can be applied only to the block that is read. And so, a block will be copied only if it is both written and read. In some cases, there may be very little intersection between the two (and so, very little copying).</p>
<p style="direction:ltr;">So basically, COWARD is just a (non-)fancy name for an array of <a href="http://en.wikipedia.org/wiki/Futures_and_promises" target="_blank">promises </a>(not to be confused with a field of dreams). The (possible) novelty is in the way this array is created and used: transparently, and relatively efficiently. Note that, like the previous proposal, it provides little value in situations where the all of the data is altered or read. However, I argue it will significantly improve performance in cases where only part of the data is read and written.</p>
<p>It can, for instance, be useful in cases where an algorithm works on COWed data (which happens quite often) and provides more processing than the user requires. Using this method, only blocks that the user requests are copied &#8212; and if the calculations themselves are lazy &#8212; processed. And all of it transparent to both the user and the implementer of the algorithm .</p>
<p>Here&#8217;s to lazier COWs!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erezsh.wordpress.com/161/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erezsh.wordpress.com/161/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/erezsh.wordpress.com/161/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/erezsh.wordpress.com/161/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/erezsh.wordpress.com/161/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/erezsh.wordpress.com/161/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/erezsh.wordpress.com/161/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/erezsh.wordpress.com/161/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/erezsh.wordpress.com/161/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/erezsh.wordpress.com/161/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=161&subd=erezsh&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://erezsh.wordpress.com/2009/06/21/lazier-copy-on-write/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">erezsh</media:title>
		</media:content>
	</item>
		<item>
		<title>PySnippets &#8211; improving code reuse</title>
		<link>http://erezsh.wordpress.com/2009/06/02/pysnippets-improving-code-reuse/</link>
		<comments>http://erezsh.wordpress.com/2009/06/02/pysnippets-improving-code-reuse/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 12:06:41 +0000</pubDate>
		<dc:creator>erezsh</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[import]]></category>
		<category><![CDATA[reuse]]></category>
		<category><![CDATA[snippet]]></category>
		<category><![CDATA[utility]]></category>
		<category><![CDATA[wikidot]]></category>

		<guid isPermaLink="false">http://erezsh.wordpress.com/?p=149</guid>
		<description><![CDATA[For a long time now, I&#8217;ve been hindered by the issue of utilities, or snippets. These are convenience functions and classes that are too small or too incomplete to justify a library, yet are useful enough to be used.
I&#8217;ve posted a few on my blog: Namespaces, X and now FileDict. Others I didn&#8217;t post, and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=149&subd=erezsh&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>For a long time now, I&#8217;ve been hindered by the issue of utilities, or snippets. These are convenience functions and classes that are too small or too incomplete to justify a library, yet are useful enough to be used.<br />
I&#8217;ve posted a few on my blog: Namespaces, X and now FileDict. Others I didn&#8217;t post, and include a priority queue, an A* implementation, a lazy-list, an LRU memoizer, etc.  You probably have a few of those. I know because I see them on snippet sites.</p>
<p>However, I rarely actually use these in my code. I really want to. But once your code spans more than one file, you usually need to make a proper installation, or at least trouble your &#8220;users&#8221; a bit more. Usually saving a few lines just isn&#8217;t worth the trouble. Copy-pasting the snippet into the file is sometimes the solution, but it really pains me that I&#8217;ll have to re-paste it every time I improve my snippet.</p>
<p>I&#8217;m sure some of you looked at my snippets, or other people&#8217;s, thought &#8220;cool&#8221;, but never used them, simply because it was too much trouble.</p>
<p>Paradoxically, this is especially true when writing snippets. They are just one small file, and using another snippet would probably make them too hard to distribute. This is a magic-circle, for-ever limiting our snippets to a low level of sophistication, and discouraging re-use.</p>
<p>I want to break that circle. I want to create an economy of snippets, increasingly building on each other, eventually creating a &#8220;standard library&#8221; of their own. But how would one do that? I have one suggestion, along with a proof-of-concept, which I will present here.</p>
<h2><strong>PySnippets</strong></h2>
<p><a title="PySnippets" href="http://pysnippets.wikidot.com" target="_blank">PySnippets</a> is my attempt of making snippets usable. It&#8217;s comprised of two solutions &#8211; a server and a client.</p>
<ol>
<li>Server - <strong>A website for uploading snippets</strong>. Simple enough. You can rate them, tag them, discuss them, offer some documentation and of-course post newer versions.</li>
<li>Client - <strong>A python module that automagically imports snippets from the web</strong>. Essentially, it downloads the snippets you request to a cache, imports them if they&#8217;re already there, and periodically searches for updates.</li>
</ol>
<p>The server is structured in a predictable way, so that the client knows how to fetch a snippet just by its name.</p>
<p><strong>The Client</strong></p>
<p>Here&#8217;s a usage example with my current client implementation, I creatively call &#8220;snippets&#8221;:</p>
<pre class="brush: python;">
import snippets
antigravity = snippets.get('antigravity')  # &quot;snippet-import&quot;
antigravity.start(mode='xkcd')
</pre>
<p>Easy as that!</p>
<p>The <em>snippets.get</em> function looks for the module in the local snippets-cache. If it&#8217;s there, <em>get</em> just imports it and returns the module. If it&#8217;s not, it queries the server for a snippet called &#8220;antigravity&#8221; (names are unique), stores it in the cache, and the imports it. What the user notices is a 2-second pause the first time he ever imports that snippet, and nothing else from then on.</p>
<p>You can specify to download a specific version, like this:</p>
<pre class="brush: python;">
filedict = snippets.get('filedict', version=0.1)
</pre>
<p><strong>Auto-Updating Snippets</strong></p>
<p style="direction:ltr;">The current implementation also includes an &#8220;auto-update&#8221; feature: Periodically, before importing a module, the client surveys the server for a newer version of it. If a newer version exists, it downloads it to the cache and continues with the import.</p>
<p style="direction:ltr;">Auto-updates can be disabled in a parameter to <em>get</em>.</p>
<p style="direction:ltr;"><strong>The Server</strong></p>
<p style="direction:ltr;">The server is yet another service to upload snippets, however it has a slightly unusual design (which no other snippet site I know of has):</p>
<ul>
<li> A URL to a snippet is easy to deduce given its name.</li>
<li>There is a conscious (though simple) support for versions.</li>
<li>To increase reliability and trust (more on that later), <span style="text-decoration:underline;">uploaded snippets cannot be altered</span> (but a new version can be issued)</li>
</ul>
<p>Since I know very little about administration and server-maintenance, I chose wikidot.com to host my POC web-site. They have an elaborate support for permissions and most of the features I need, such as the ability to rate, tag and discuss snippets.</p>
<p><strong>Trust</strong></p>
<p>Perhaps the biggest issue with such a system is trust. Since you&#8217;re running code which resides online, you have to trust me not to maliciously alter the snippets, and also you have to trust the author of the snippet not to do so.</p>
<div style="direction:ltr;">As a partial solution, uploaded files cannot be altered: Not edited, nor renamed, nor deleted, etc. So if specify a particular snippet version, it is guaranteed that it will never change (I may commit changes by request, but I will audit them myself).</div>
<div style="direction:ltr;">If you decide to use the latest version of a snippet (that is, not specify a version), please make sure you trust its author.</div>
<p>Perhaps higher-ups in the Python community would like to take some sponsorship of the project, removing the remaining trust-issues with the administrator (that&#8217;s me).</p>
<h2><strong>Implications</strong></h2>
<ul>
<li>To distribute your snippets, all you need is for the reciever to have an internet connection, and the snippets client.</li>
<li>If you&#8217;re sending someone code, you can attach the client (it&#8217;s rather small, too), and just import away. The reciever will benefit from improvements and bugfixes to your snippets.</li>
<li>You can use other people&#8217;s snippets just as easily, as long as you trust them.</li>
<li>Snippets can now build on each other without worrying too much.</li>
</ul>
<p><strong>What if my user is offline?</strong></p>
<p>Then probably PySnippets isn&#8217;t for him.</p>
<p>However, I do have some ideas, and might implement them if there is sufficient demand.</p>
<h2><strong>Afterword</strong></h2>
<p>PySnippets is my humble attempt at solving the utility/snippet reuse problems. I hope you like it and find it useful.</p>
<p>Please <a title="PySnippets" href="http://pysnippets.wikidot.com/" target="_blank">try it</a>!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erezsh.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erezsh.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/erezsh.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/erezsh.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/erezsh.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/erezsh.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/erezsh.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/erezsh.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/erezsh.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/erezsh.wordpress.com/149/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=149&subd=erezsh&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://erezsh.wordpress.com/2009/06/02/pysnippets-improving-code-reuse/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">erezsh</media:title>
		</media:content>
	</item>
		<item>
		<title>FileDict &#8211; bug-fixes and updates</title>
		<link>http://erezsh.wordpress.com/2009/05/31/filedict-bug-fixes-and-updates/</link>
		<comments>http://erezsh.wordpress.com/2009/05/31/filedict-bug-fixes-and-updates/#comments</comments>
		<pubDate>Sun, 31 May 2009 16:15:41 +0000</pubDate>
		<dc:creator>erezsh</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[bugfix]]></category>
		<category><![CDATA[dict]]></category>
		<category><![CDATA[FileDict]]></category>
		<category><![CDATA[persistent]]></category>
		<category><![CDATA[sqlite]]></category>
		<category><![CDATA[sqlite3]]></category>

		<guid isPermaLink="false">http://erezsh.wordpress.com/?p=145</guid>
		<description><![CDATA[In my previous post I introduced FileDict. I did my best to get it right the first time, but as we all know, this is impossible for any non-trivial piece of code.
I want to thank everyone for their comments and remarks. It&#8217;s been very helpful.
The Unreliable Pickle
A special thanks goes to the mysterious commenter &#8220;R&#8221;, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=145&subd=erezsh&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In my <a href="http://erezsh.wordpress.com/2009/05/24/filedict-a-persistent-dictionary-in-python/">previous post</a> I introduced FileDict. I did my best to get it right the first time, but as we all know, this is impossible for any non-trivial piece of code.<br />
I want to thank everyone for their comments and remarks. It&#8217;s been very helpful.</p>
<p><strong>The Unreliable Pickle</strong></p>
<p>A special thanks goes to the mysterious commenter &#8220;R&#8221;, for pointing out that pickling identical objects may produce different strings (!), which are therefor inadequate to be used as keys. And my FileDict indeed suffered from this bug, as this example shows:</p>
<pre class="brush: python;">
&gt;&gt;&gt; key = (1, u'foo')
&gt;&gt;&gt; d[(1, u'foo')] = 4
&gt;&gt;&gt; d[(1, u'foo')]
4
&gt;&gt;&gt; d[key]
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
  File &quot;filedict.py&quot;, line 64, in __getitem__
    raise KeyError(key)
KeyError: (1, u'foo')
</pre>
<p>And if that&#8217;s not bad enough:</p>
<pre class="brush: python;">
&gt;&gt;&gt; d[key] = 5
&gt;&gt;&gt; list(d.items())
[['a', 3], [(1, 2), 3], [(1, u'foo'), 4], [(1, u'foo'), 5]]
</pre>
<p>Ouch.<br />
I&#8217;ve rewritten the entire storing mechanism to poll only on hash and compare keys after unpickling. This may be a bit slower, but I don&#8217;t (and shouldn&#8217;t) expect many colliding hashes anyway.<br />
Bug is fixed.</p>
<p><strong>DictMixin</strong></p>
<p>Under popular demand, I&#8217;m now inheriting from DictMixin. It&#8217;s made my code a bit shorter, and was not at all painful.</p>
<p><strong>Copy and Close</strong></p>
<p>I no longer close the database on __del__, and instead I rely on the garbage collector. It seems to close the database on time, and it allows to one copy the dictionary (which, of course, will all be always have the same keys, but doesn&#8217;t have to have the same behavior or attributes).</p>
<p><strong>New Source Code</strong></p>
<p>Is available <a href="http://erez.wikidot.com/filedict-0-2-code">here</a></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erezsh.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erezsh.wordpress.com/145/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/erezsh.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/erezsh.wordpress.com/145/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/erezsh.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/erezsh.wordpress.com/145/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/erezsh.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/erezsh.wordpress.com/145/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/erezsh.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/erezsh.wordpress.com/145/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=145&subd=erezsh&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://erezsh.wordpress.com/2009/05/31/filedict-bug-fixes-and-updates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">erezsh</media:title>
		</media:content>
	</item>
		<item>
		<title>FileDict &#8211; a Persistent Dictionary in Python</title>
		<link>http://erezsh.wordpress.com/2009/05/24/filedict-a-persistent-dictionary-in-python/</link>
		<comments>http://erezsh.wordpress.com/2009/05/24/filedict-a-persistent-dictionary-in-python/#comments</comments>
		<pubDate>Sun, 24 May 2009 14:59:55 +0000</pubDate>
		<dc:creator>erezsh</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[dict]]></category>
		<category><![CDATA[persistent]]></category>
		<category><![CDATA[sqlite]]></category>
		<category><![CDATA[sqlite3]]></category>

		<guid isPermaLink="false">http://erezsh.wordpress.com/?p=137</guid>
		<description><![CDATA[The result is a dictionary which at all-times exists as a file, has virtually no size limit, and can be accessed by several processes concurrently.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=137&subd=erezsh&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Python&#8217;s dictionary is possibly the most useful construct in the language.  And I argue that for some purposes, mapping it to a file (in real-time) can be even more useful.</p>
<p><strong>Why?</strong></p>
<p>The dictionary resides in memory, and so has three main &#8220;faults&#8221;:</p>
<ol>
<li>It only lasts as long as your program does.</li>
<li>It occupies memory that might be useful for other, more commonly accessed, data.</li>
<li>It is limited to how much memory your machine has.</li>
</ol>
<p>The first can be solved by pickling and unpickling the dictionary, but will not survive an unexpected shutdown (even putting the pickling in a try-finally block won&#8217;t protect it against all errors).</p>
<p><strong>FileDict</strong></p>
<p>FileDict is a dictionary interface I wrote, that saves and loads its data from a file using keys. Current version uses Sqlite3 to provide consistency, and as a by-product, <a title="ACID" href="http://en.wikipedia.org/wiki/ACID" target="_blank">acidity</a>.</p>
<p>The result is a dictionary which at all-times exists as a file, has virtually no size limit, and can be accessed by several processes concurrently.</p>
<p>It is meant as a quick-and-simple general-purpose solution. It is rarely the best solution, but it is usually good enough.</p>
<p>Performance obviously cannot compare to the builtin dictionary, but it is reasonable and of low complexity (refer to sqlite for more details on <em>that</em>).</p>
<p><strong>Uses</strong></p>
<p>FileDict can be used for many purposes, including:</p>
<ul>
<li>Saving important data in a convinient manner</li>
<li>Managing large amounts of data in dictionary form, without the mess of implementing paging or other complex solutions</li>
<li>Communication between processes (sqlite supports multiple connections and implements ACID)</li>
</ul>
<p><strong>Examples</strong></p>
<pre class="brush: python;">
$ python
&gt;&gt;&gt; import filedict
&gt;&gt;&gt; d=filedict.FileDict(filename=&quot;example.dict&quot;)
&gt;&gt;&gt; d['bla'] = 10
&gt;&gt;&gt; d[(2,1)] = ['hello', (1,2) ]
-- exit --
$ python
&gt;&gt;&gt; import filedict
&gt;&gt;&gt; d=filedict.FileDict(filename=&quot;example.dict&quot;)
&gt;&gt;&gt; print d['bla']
10
&gt;&gt;&gt; print d.items()
[['bla', 10], [(2, 1), ['hello', (1, 2)]]]
&gt;&gt;&gt; print dict(d)
{'bla': 10, (2, 1): ['hello', (1, 2)]}
</pre>
<pre class="brush: python;">
&gt;&gt;&gt; d=filedict.FileDict(filename=&quot;try.dict&quot;)
&gt;&gt;&gt; with d.batch:  # using .batch suspend commits, making a batch of changes quicker
&gt;&gt;&gt;    for i in range(100000):
&gt;&gt;&gt;            d[i] = i**2
(takes about 8 seconds on my comp)
&gt;&gt;&gt; print len(d)
100000
&gt;&gt;&gt; del d[103]
&gt;&gt;&gt; print len(d)
99999
</pre>
<p><strong>Limitations</strong></p>
<p><strong></strong></p>
<p><strong></strong></p>
<p><strong></strong></p>
<ul>
<li>All data (keys and values) must be pickle-able</li>
<li>Keys must be hashable (<em>perhaps this should be removed by hashing the pickled key</em>)</li>
</ul>
<p><strong>Source Code</strong></p>
<p>Is availible <a href="http://erez.wikidot.com/filedict-0-1-code">in here</a></p>
<p><strong>Future</strong></p>
<p>Additions in the future may include:</p>
<ul>
<li>An LRU-cache for fetching entries</li>
<li>A storage strategy different than Sqlite</li>
</ul>
<p>Other suggestions?</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erezsh.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erezsh.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/erezsh.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/erezsh.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/erezsh.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/erezsh.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/erezsh.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/erezsh.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/erezsh.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/erezsh.wordpress.com/137/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=137&subd=erezsh&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://erezsh.wordpress.com/2009/05/24/filedict-a-persistent-dictionary-in-python/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">erezsh</media:title>
		</media:content>
	</item>
		<item>
		<title>Raphael and a Prophecy</title>
		<link>http://erezsh.wordpress.com/2009/03/07/raphael-and-a-prophecy/</link>
		<comments>http://erezsh.wordpress.com/2009/03/07/raphael-and-a-prophecy/#comments</comments>
		<pubDate>Sat, 07 Mar 2009 09:59:28 +0000</pubDate>
		<dc:creator>erezsh</dc:creator>
				<category><![CDATA[Web Programming]]></category>
		<category><![CDATA[Raphael]]></category>
		<category><![CDATA[vector graphics]]></category>
		<category><![CDATA[web graphics]]></category>

		<guid isPermaLink="false">http://erezsh.wordpress.com/?p=127</guid>
		<description><![CDATA[you can create complex vector graphics that work in almost every browser<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=127&subd=erezsh&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>More than once I have wasted my time in attempt to introduce graphics into the webpage, some of these attempts are recorded in this very blog: First were my <a href="/2008/07/31/drawing-diagonal-lines-with-css/">lines in CSS</a>, followed by <a href="/2008/11/25/rotating-cube-in-javascript/">rotating rectangles</a>. I say &#8220;wasted&#8221; because I have now found <a href="http://raphaeljs.com/">Raphaël</a>, and I&#8217;m in love.</p>
<p><strong>Raphaël</strong></p>
<p>What is it? Their site is too modest, claiming &#8220;Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web&#8221;.<br />
While true, it is also a most ambitious project to change the way the web looks, whether they mean to or not.<br />
All (popular) browsers support vector graphics: IE supports VML, and all other browsers support SVG. By implementing both languages and switching between them, you can create complex vector graphics that work in almost every browser.<br />
This idea was new to me, at least, and I think it&#8217;s great. Now Raphaël comes along and does it for you. Nice.</p>
<p><strong>My Prophecy</strong><br />
Vector graphics (VG) will become more popular. As VG libraries mature (and Raphaël is already in good shape), VG on the web would become so easy that anyone could use them, and many would. Soon enough you will have beautiful interactive GUIs. At fiirst snippets and demos, then complete libraries for everyone to use. What more can it do? Maybe interactive animations, maybe just add some spice to websites.<br />
It probably won&#8217;t bury Flash, but I expect it would be a competition.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erezsh.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erezsh.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/erezsh.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/erezsh.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/erezsh.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/erezsh.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/erezsh.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/erezsh.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/erezsh.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/erezsh.wordpress.com/127/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=127&subd=erezsh&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://erezsh.wordpress.com/2009/03/07/raphael-and-a-prophecy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">erezsh</media:title>
		</media:content>
	</item>
		<item>
		<title>The Evils Of Positional Arguments</title>
		<link>http://erezsh.wordpress.com/2009/01/16/the-evils-of-positional-arguments/</link>
		<comments>http://erezsh.wordpress.com/2009/01/16/the-evils-of-positional-arguments/#comments</comments>
		<pubDate>Fri, 16 Jan 2009 14:49:53 +0000</pubDate>
		<dc:creator>erezsh</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://erezsh.wordpress.com/?p=123</guid>
		<description><![CDATA[A few days ago I found myself writing pure ansi C code, after over two years of not touching it at all. In fact, these two years consisted mostly of Python, and a little of C#, both very far from it. While coding away, trying to get re-accustumed to mallocs and frees, return values instead [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=123&subd=erezsh&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>A few days ago I found myself writing pure ansi C code, after over two years of not touching it at all. In fact, these two years consisted mostly of Python, and a little of C#, both very far from it. While coding away, trying to get re-accustumed to mallocs and frees, return values instead of exceptions and pointer arithmatic, I had to perform a memcpy. Very easy, of course, but I could not for the life of me remember how to call it. I remembered rather vividly that it had 3 arguments, named &#8216;dst&#8217;, &#8217;src&#8217; and &#8216;len&#8217;, the first two being void* and the latter.. perhaps plain int? But in which order they came, I could not recall. Now, that is not so evil, of course, because a quick look at the C reference refreshed my memory (until next time). This repeated with other functions (such as memset). But only when it started to happen with my own functions, I realized how unnatural it is for me, to remember things by order and not by name. Names allow us to establish a context, to find reasoning. Also, we are (relatively) good at remembering names.</p>
<p>By using position as a way for transferring parameters, we are essentially calling them &#8220;one&#8221;, &#8220;two&#8221;, &#8220;three&#8221; and etc., which are still names, but are devoid of context or meaning, and are the same for every function. It is not only hard to remember the right order; we can endure it (as reality proves), but it makes our code less readable, less natural.</p>
<p>Also, it complicates changing existing APIs. Move an argument from its position, and you have to change the position everywhere in the code. This can easily lead to subtle bugs (consider switching dst and src, it may be very hard to find where this happened!). So if you append parameters, they must come in the end, which somtimes does not make much sense.</p>
<p>While all programming languages (that I know of) sin in this evil of positionality , one device takes it one step ahead: Regular expressions. Specfically, RE Substitution. Not only do you address its matches using numbers, but actually figuring out which number goes to which match can be confounding. I cannot count how many bugs this must have produced.</p>
<p><strong>In conclusion:</strong></p>
<p>Design your systems differently.<br />
Let computers count. Let humans use names!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erezsh.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erezsh.wordpress.com/123/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/erezsh.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/erezsh.wordpress.com/123/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/erezsh.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/erezsh.wordpress.com/123/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/erezsh.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/erezsh.wordpress.com/123/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/erezsh.wordpress.com/123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/erezsh.wordpress.com/123/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=123&subd=erezsh&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://erezsh.wordpress.com/2009/01/16/the-evils-of-positional-arguments/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">erezsh</media:title>
		</media:content>
	</item>
		<item>
		<title>Rotating Cube in JavaScript</title>
		<link>http://erezsh.wordpress.com/2008/11/25/rotating-cube-in-javascript/</link>
		<comments>http://erezsh.wordpress.com/2008/11/25/rotating-cube-in-javascript/#comments</comments>
		<pubDate>Tue, 25 Nov 2008 19:58:38 +0000</pubDate>
		<dc:creator>erezsh</dc:creator>
				<category><![CDATA[Web Programming]]></category>
		<category><![CDATA[3d]]></category>
		<category><![CDATA[cube]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JS]]></category>

		<guid isPermaLink="false">http://erezsh.wordpress.com/?p=121</guid>
		<description><![CDATA[My CSS-Parrot gave me an appetite for more in-browser graphics. This, led to my newest creation: A rotating &#8220;3D&#8221; cube, written with JavaScript.
Check it out here: http://kanelynchsucks.com/sfsr/rot_cube.html
(glory to Tzahi for hosting it)
Please note, this cube is not really 3D.  I just hacked it together using a couple of tricks, which I think are rather clever.
My [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=121&subd=erezsh&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>My CSS-Parrot gave me an appetite for more in-browser graphics. This, led to my newest creation: A rotating &#8220;3D&#8221; cube, written with JavaScript.</p>
<p>Check it out here: <a title="Rotating Cube" href="http://kanelynchsucks.com/sfsr/rot_cube.html" target="_blank">http://kanelynchsucks.com/sfsr/rot_cube.html</a></p>
<p>(glory to Tzahi for hosting it)</p>
<p>Please note, this cube is <em>not really 3D</em>.  I just hacked it together using a couple of tricks, which I think are rather clever.</p>
<p>My next post (or more) will explain thoroughly how I made the cube and the tricks that I used. But I highly recommend you, the readers of this blog, to try and figure it out yourself. It can be a fun exercise. The actual code is very readable, and the only mystery is &#8211; how did I do it?</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erezsh.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erezsh.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/erezsh.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/erezsh.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/erezsh.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/erezsh.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/erezsh.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/erezsh.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/erezsh.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/erezsh.wordpress.com/121/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=121&subd=erezsh&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://erezsh.wordpress.com/2008/11/25/rotating-cube-in-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">erezsh</media:title>
		</media:content>
	</item>
		<item>
		<title>Pickling Python Expressions</title>
		<link>http://erezsh.wordpress.com/2008/11/12/pickling-python-expressions/</link>
		<comments>http://erezsh.wordpress.com/2008/11/12/pickling-python-expressions/#comments</comments>
		<pubDate>Wed, 12 Nov 2008 19:41:54 +0000</pubDate>
		<dc:creator>erezsh</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[pickle]]></category>
		<category><![CDATA[X]]></category>

		<guid isPermaLink="false">http://erezsh.wordpress.com/?p=115</guid>
		<description><![CDATA[My last post introduced the concept of X, a class which &#8220;absorbs&#8221; operations and behaves like a function.
As many people pointed out, this was merely a syntactic alternative to lambda. You may like it, you may not.
Now, after a rewrite, X can now be pickled. But let me explain first.
Python lambdas cannot be pickled. In [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=115&subd=erezsh&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>My last post introduced the concept of X, a class which &#8220;absorbs&#8221; operations and behaves like a function.<br />
As many people pointed out, this was merely a syntactic alternative to lambda. You may like it, you may not.<br />
Now, after a rewrite, X can now be pickled. But let me explain first.</p>
<p>Python lambdas cannot be pickled. In fact, python <em>code</em> cannot be pickled.<br />
Pickling an object, aka serializing, is converting the object&#8217;s state (that is, its data) to a string, which can at a later time be unpickled to re-create the object with that state. The unpickling process instanciates that class, assuming it has not changed, and updating the new instance&#8217;s state to the pickled one. Python code is never stored.</p>
<p>Trying to pickle a class or a function might appear to work, but it does not really pickle it; it simply pickles the reference to it (and its state). Unpickling the string in a new terminal would prove that (as would a quick analysis of resulting string).</p>
<p>Attempts to pickle methods, nested functions or lambdas fail on the spot. That is because a reference to them cannot be kept (Actually, it can be. But they are rather volatile, so it might not be wise). Eventually, python code, or even expressions, cannot be pickled.</p>
<p>This brings me back to X. X allows you to do just that:</p>
<pre>
&gt;&gt;&gt; expr = 1 + (X + 3) * 4
&gt;&gt;&gt; s = pickle.dumps(expr)

(destory objects, change objects, switch an interpreter, whatever you wish)

&gt;&gt;&gt; expr2 = pickle.loads(s)
&gt;&gt;&gt; expr2(5)
33
</pre>
<p>By using X, the programmer can blend dynamic code with his data, and still be able to pickle it.<br />
I believe this removes a very big limitation.</p>
<p>Just to be fair, I will note that there is another way to achieve this: Keep your expressions in a string, and eval it when you need it run. I highly recommend not doing it.</p>
<p>X&#8217;s new source code (a bit cryptic, but it&#8217;s the best I could do. Suggestions for simplification are welcomed) :</p>
<pre class="brush: python;">
&quot;&quot;&quot;
x.py

Author: Erez Sh.
Date  : 11/11/2008
&quot;&quot;&quot;

import operator

def identity(x):
	return x

class _Return(object):
	&quot;Pickle-able!&quot;
	def __init__(self, value):
		self._value = value

	def __call__(self, *args):
		return self._value

class _Partial(object):
	&quot;Pickle-able!&quot;
	def __init__(self, callable, *args):
		self._callable = callable
		self._args = args

	def __call__(self, *args, **kwargs):
		args = self._args + args
		return self._callable(*args)

class _X(object):
	def __init__(self, func, *args_to_run):
		self.__func = func
		self.__args_to_run = tuple(args_to_run)

	def __getstate__(self):
		return self.__func, self.__args_to_run
	def __setstate__(self, state):
		self.__func, self.__args_to_run = state
	def __reduce__(self):
		#raise Exception(&quot;Deprecated!&quot;)
		return object.__reduce__(self)

	def __apply_un_func(self, func ):
		return _X(func, _Partial(self))
	def __apply_bin_func(self, func, arg ):
		return _X(func, _Partial(self), _Return(arg))
	def __apply_rbin_func(self, func, arg ):
		return _X(func, _Return(arg), _Partial(self))
	def __apply_multargs_func(self, func, *args ):
		return _X(func, _Partial(self), *map(_Return,args))

	def __call__(self, arg):
		return self.__func(*[x(arg) for x in self.__args_to_run])

	def __getattr__(self, attr):
		return self.__apply_bin_func( getattr, attr )

	def call(self, *args, **kwargs):
		return self.__apply_multargs_func( apply, args, kwargs)

	# Containers
	def __getitem__(self, other):
		return self.__apply_bin_func( operator.getitem, other )
	def __getslice__(self, a,b=None,c=None):
		return self.__apply_bin_func( operator.getslice, other )
	def in_(self, other):
		return self.__apply_bin_func( operator.contains, other )

	# Arith
	def __add__(self, other):
		return self.__apply_bin_func( operator.add, other )
	def __sub__(self, other):
		return self.__apply_bin_func( operator.sub, other )
	def __mul__(self, other):
		return self.__apply_bin_func( operator.mul, other )
	def __div__(self, other):
		return self.__apply_bin_func( operator.div, other )
	def __floordiv__(self, other):
		return self.__apply_bin_func( operator.floordiv, other )
	def __truediv__(self, other):
		return self.__apply_bin_func( operator.truediv, other )
	def __mod__(self, other):
		return self.__apply_bin_func( operator.mod, other )
	def __pow__(self, other):
		return self.__apply_bin_func( operator.pow, other )

	def __radd__(self, other):
		return self.__apply_rbin_func( operator.add, other )
	def __rsub__(self, other):
		return self.__apply_rbin_func( operator.sub, other )
	def __rmul__(self, other):
		return self.__apply_rbin_func( operator.mul, other )
	def __rdiv__(self, other):
		return self.__apply_rbin_func( operator.div, other )
	def __rfloordiv__(self, other):
		return self.__apply_rbin_func( operator.floordiv, other )
	def __rtruediv__(self, other):
		return self.__apply_rbin_func( operator.truediv, other )
	def __rmod__(self, other):
		return self.__apply_rbin_func( operator.mod, other )
	def __rpow__(self, other):
		return self.__apply_rbin_func( operator.pow, other )

	# bitwise
	def __and__(self, other):
		return self.__apply_bin_func( operator.and_, other )
	def __or__(self, other):
		return self.__apply_bin_func( operator.or_, other )
	def __xor__(self, other):
		return self.__apply_bin_func( operator.xor, other )

	def __rand__(self, other):
		return self.__apply_rbin_func( operator.and_, other )
	def __ror__(self, other):
		return self.__apply_rbin_func( operator.or_, other )
	def __rxor__(self, other):
		return self.__apply_rbin_func( operator.xor, other )

	def __rshift__(self, other):
		return self.__apply_bin_func( operator.rshift, other )
	def __lshift__(self, other):
		return self.__apply_bin_func( operator.lshift, other )

	# Comparison
	def __lt__(self, other):
		return self.__apply_bin_func( operator.lt, other )
	def __le__(self, other):
		return self.__apply_bin_func( operator.le, other )
	def __eq__(self, other):
		return self.__apply_bin_func( operator.eq, other )
	def __ne__(self, other):
		return self.__apply_bin_func( operator.ne, other )
	def __ge__(self, other):
		return self.__apply_bin_func( operator.ge, other )
	def __gt__(self, other):
		return self.__apply_bin_func( operator.gt, other )

	def __abs__(self):
		return self.__apply_un_func( abs )
	def __neg__(self):
		return self.__apply_un_func( operator.neg )

X = _X(identity, identity)
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erezsh.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erezsh.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/erezsh.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/erezsh.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/erezsh.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/erezsh.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/erezsh.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/erezsh.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/erezsh.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/erezsh.wordpress.com/115/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=115&subd=erezsh&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://erezsh.wordpress.com/2008/11/12/pickling-python-expressions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">erezsh</media:title>
		</media:content>
	</item>
		<item>
		<title>Fun While Avoiding Lambda (Python)</title>
		<link>http://erezsh.wordpress.com/2008/11/01/fun-while-avoiding-lambda/</link>
		<comments>http://erezsh.wordpress.com/2008/11/01/fun-while-avoiding-lambda/#comments</comments>
		<pubDate>Sat, 01 Nov 2008 18:31:47 +0000</pubDate>
		<dc:creator>erezsh</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[X]]></category>

		<guid isPermaLink="false">http://erezsh.wordpress.com/?p=109</guid>
		<description><![CDATA[Readers, meet X. X is a class I wrote in Python as an alternative to using lambda. It has two main features:

It acts as an identity function ( so X(3) == 3, etc. )
When performing operations on it, it returns a new class that acts as a corresponding function.

Let me explain. Doing X+2 will return [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=109&subd=erezsh&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><strong>Readers, meet X</strong>. X is a class I wrote in Python as an alternative to using lambda. It has two main features:</p>
<ol>
<li>It acts as an identity function ( so X(3) == 3, etc. )</li>
<li>When performing operations on it, it returns a new class that acts as a corresponding function.</li>
</ol>
<p>Let me explain. Doing X+2 will return a new class that whenever called with an argument, will return that argument added with 2. So:</p>
<p><code>&gt;&gt;&gt; map( X+2, [1, 2, 3] )<br />
[3, 4, 5]</code></p>
<p><code>&gt;&gt;&gt; filter( X&gt;0, [5, -3, 2, -1, 0, 13] )<br />
[5, 2, 13]</code></p>
<p><code>&gt;&gt;&gt; l = ["oh", "brave", "new", "world"]<br />
&gt;&gt;&gt; sorted(l,key=X[-1])<br />
['world', 'brave', 'oh', 'new']</code></p>
<p>These operations can be chained:</p>
<p><code>&gt;&gt;&gt; map(2**(X+1), range(10))<br />
[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]</code></p>
<p><code>&gt;&gt;&gt; map( "P" + X[3:]*2 + "!", ["Hello", "Suzzy"] )<br />
['Plolo!', 'Pzyzy!']</code></p>
<p><strong>Caveats</strong></p>
<p>X has a few limitations.</p>
<ul>
<li>Using X twice in the same expression probably won&#8217;t work (this can be solved)</li>
<li>Since calling X evaluates it, it can&#8217;t emulate method calls. For that you have to do use call, like: X.upper.call() (&#8216;hello&#8217;) &#8211;&gt; &#8216;HELLO&#8217;.</li>
<li>Not all operations can be &#8220;captured&#8221;. For example, the &#8220;in&#8221; operator. For that you have to use X.in_( &#8230; ), like: X.in_(range(10)) (5) &#8211;&gt; True</li>
<li>Not all attributes will be accessible</li>
<li>More problems? Likely.</li>
</ul>
<p><strong>Conclusion</strong></p>
<p>While not innovative nor a complete solution, I believe X can be a useful replacement for some uses of anonymous functions, providing a shorter and simpler syntax which is easier to read and understand.</p>
<p>It is provided here in full, in hope that it will be useful to my readers (Improvements and fixes are welcome):</p>
<pre class="brush: python;">
class _X(object):
	def __init__(self, func):
		self.__func = func

	def __call__(self, arg):
		return self.__func(arg)

	def __getattr__(self, attr):
		return _X(lambda x: getattr(self(x), attr))
	def call(self, *args, **kwargs):
		return _X(lambda x: self(x)(*args,**kwargs))

	# Containers
	def __getitem__(self, other):
		return _X(lambda x: self(x)[other])
	def __getslice__(self, a,b=None,c=None):
		return _X(lambda x: self(x)[a:b:c])
	def in_(self, other):
		return _X(lambda x: self(x) in other)

	# Arith
	def __add__(self, other):
		return _X(lambda x: self(x) + other)
	def __sub__(self, other):
		return _X(lambda x: self(x) - other)
	def __mul__(self, other):
		return _X(lambda x: self(x) * other)
	def __div__(self, other):
		return _X(lambda x: self(x) / other)
	def __floordiv__(self, other):
		return _X(lambda x: self(x) // other)
	def __mod__(self, other):
		return _X(lambda x: self(x) % other)
	def __pow__(self, other):
		return _X(lambda x: self(x) ** other)

	def __radd__(self, other):
		return _X(lambda x: other + self(x))
	def __rsub__(self, other):
		return _X(lambda x: other - self(x))
	def __rmul__(self, other):
		return _X(lambda x: other * self(x))
	def __rdiv__(self, other):
		return _X(lambda x: other / self(x))
	def __rfloordiv__(self, other):
		return _X(lambda x: other // self(x))
	def __rmod__(self, other):
		return _X(lambda x: other % self(x))
	def __rpow__(self, other):
		return _X(lambda x: other ** self(x))

	# bitwise
	def __and__(self, other):
		return _X(lambda x: self(x) &amp; other)
	def __or__(self, other):
		return _X(lambda x: self(x) | other)
	def __xor__(self, other):
		return _X(lambda x: self(x) ^ other)

	def __rand__(self, other):
		return _X(lambda x: other &amp; self(x))
	def __ror__(self, other):
		return _X(lambda x: other | self(x))
	def __rxor__(self, other):
		return _X(lambda x: other ^ self(x))

	def __rshift__(self, other):
		return _X(lambda x: self(x) &gt;&gt; other)
	def __lshift__(self, other):
		return _X(lambda x: self(x) &lt;&lt; other)

	# Comparison
	def __lt__(self, other):
		return _X(lambda x: self(x) &lt; other)
	def __le__(self, other):
		return _X(lambda x: self(x) &lt;= other)
	def __eq__(self, other):
		return _X(lambda x: self(x) == other)
	def __ne__(self, other):
		return _X(lambda x: self(x) != other)
	def __ge__(self, other):
		return _X(lambda x: self(x) &gt;= other)
	def __gt__(self, other):
		return _X(lambda x: self(x) &gt; other)

	def __abs__(self):
		return _X(lambda x: abs(self(x)))

X = _X(lambda x:x)
</pre>
<p>Put it in x.py and import as:<br />
from x import X</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erezsh.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erezsh.wordpress.com/109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/erezsh.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/erezsh.wordpress.com/109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/erezsh.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/erezsh.wordpress.com/109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/erezsh.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/erezsh.wordpress.com/109/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/erezsh.wordpress.com/109/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/erezsh.wordpress.com/109/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=109&subd=erezsh&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://erezsh.wordpress.com/2008/11/01/fun-while-avoiding-lambda/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">erezsh</media:title>
		</media:content>
	</item>
		<item>
		<title>Namespaces in Python &#8211; Revisited</title>
		<link>http://erezsh.wordpress.com/2008/09/02/namespaces-in-python-revisited/</link>
		<comments>http://erezsh.wordpress.com/2008/09/02/namespaces-in-python-revisited/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 12:47:07 +0000</pubDate>
		<dc:creator>erezsh</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Namespace]]></category>
		<category><![CDATA[Namespaces]]></category>
		<category><![CDATA[Property]]></category>
		<category><![CDATA[Python 2.6]]></category>
		<category><![CDATA[Python 3]]></category>

		<guid isPermaLink="false">http://erezsh.wordpress.com/?p=93</guid>
		<description><![CDATA[Taking a short break from my artwork craze (but I promise more is to come), I reviewed some of the new features and changes in Python, brought by versions 2.6 and 3.0. There are many interesting features, but a very specific one caught my eye: the ability to modify existing properties.
From the documentation:
Properties now have [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=93&subd=erezsh&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Taking a short break from my artwork craze (but I promise more is to come), I reviewed some of the new features and changes in Python, brought by versions 2.6 and 3.0. There are many interesting features, but a very specific one caught my eye: the ability to modify existing properties.</p>
<p>From the <a href="http://docs.python.org/dev/whatsnew/2.6.html#other-language-changes" target="_blank">documentation</a>:</p>
<blockquote><p>Properties now have three attributes, getter, setter and deleter, that are decorators providing useful shortcuts for adding a getter, setter or deleter function to an existing property. You would use them like this:</p>
<pre>class C(object):
    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

class D(C):
    @C.x.getter
    def x(self):
        return self._x * 2

    @x.setter
    def x(self, value):
        self._x = value / 2</pre>
</blockquote>
<p>I found this very interesting. If you&#8217;re, for some reason, a frequent reader of this blog, you&#8217;d remember how in a <a href="http://erezsh.wordpress.com/2008/06/27/namespaces-lets-do-more-of-those-python-hackery/" target="_self">previous post</a> I suggested a hack to allow namespaces inside Python classes. However, it was largely incomplete because I couldn&#8217;t get it to work for properties. Perhaps now I can?</p>
<p>Now, don&#8217;t let that pretty decorator syntax mislead you. Doing:</p>
<pre>    @x.setter
    def x(self, value):
        self._x = value</pre>
<p>is exactly identical to doing:</p>
<pre>    def x_set(self, value): # Name changed to preserve 'x'
        self._x = value
    x = x.setter(x_set)</pre>
<p>And this is exactly what I was missing to complete my code.</p>
<p>So here is the new make_namespace, applying also to properties:</p>
<p>(<em>This was only tested on Python 3, but should also work for Python 2.6. It will <strong>not work on version 2.5 or lower</strong></em>)</p>
<pre class="brush: python;">
import types
def make_namespace(self, ns_cls):
    &quot;This code iterates all functions and properties in ns_cls and binds them to self&quot;
    for attr_name in dir(ns_cls):
        attr = getattr(ns_cls, attr_name)
        if type(attr) == types.FunctionType:
            setattr(ns_cls, attr_name, attr.__get__(self) )
        elif type(attr) ==  property:
            setattr( ns_cls, attr_name, attr
                    .getter( lambda x  : attr.fget(self))
                    .setter( lambda x,v: attr.fset(self,v))
                    .deleter(lambda x  : attr.fdel(self))
                )
    return ns_cls()
</pre>
<p>Notice that I can chain getter, setter, and deleter, because they all return a property object.</p>
<p>And here is a possible usage:</p>
<pre class="brush: python;">
class YetAnotherGuiWindow:
    def __init__(self, pos, size, ...):
        ...
        self._size = size
        self.spatial = make_namespace(self, self.spatial)

    class spatial:
        ...
        def _get_size(self):
            return self._size
        def _set_size(self, size):
            self._size = size
        size = property(_get_size, _set_size)
        ...

...
# Meanwhile, in my console
&gt;&gt;&gt; g.spatial.size = (100,100)
&gt;&gt;&gt; g.spatial.size
(100, 100)
&gt;&gt;&gt; g.spatial.size = (140,10)
&gt;&gt;&gt; g.spatial.size
(140, 10)
&gt;&gt;&gt; g._size
(140, 10)
</pre>
<p>I hope you&#8217;ll find this useful!</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/erezsh.wordpress.com/93/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/erezsh.wordpress.com/93/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erezsh.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erezsh.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/erezsh.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/erezsh.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/erezsh.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/erezsh.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/erezsh.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/erezsh.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/erezsh.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/erezsh.wordpress.com/93/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=erezsh.wordpress.com&blog=4049275&post=93&subd=erezsh&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://erezsh.wordpress.com/2008/09/02/namespaces-in-python-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">erezsh</media:title>
		</media:content>
	</item>
	</channel>
</rss>