<?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>Algorithm Blogs &#187; Python</title>
	<atom:link href="http://www.algorithm.co.il/blogs/index.php/category/programming/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.algorithm.co.il/blogs</link>
	<description>Algorithms, for the heck of it</description>
	<lastBuildDate>Thu, 22 Apr 2010 21:04:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>One-liner Guitar Tuner in Python</title>
		<link>http://www.algorithm.co.il/blogs/index.php/programming/python/one-liner-guitar-tuner-in-python/</link>
		<comments>http://www.algorithm.co.il/blogs/index.php/programming/python/one-liner-guitar-tuner-in-python/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 21:04:32 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Sound]]></category>
		<category><![CDATA[guitar]]></category>
		<category><![CDATA[guitar tuner]]></category>
		<category><![CDATA[one-liner]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=611</guid>
		<description><![CDATA[
On windows, assuming imports are free:


import winsound
winsound.Beep&#40;220*&#40;&#40;2**&#40;1/12.0&#41;&#41;**7&#41;, 2000&#41;



But that's just because I like to tune to E. If you prefer a more "natural looking" note, you can use A:


winsound.Beep&#40;110, 1000&#41;



But why choose at all when you can go for all of them?


&#91;winsound.Beep&#40;220*&#40;&#40;2**&#40;1/12.0&#41;&#41;**i&#41;, 500&#41; for i in &#91;7, 2, -2, -7, -12, -17&#93;&#93;



Image by Keela84
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.algorithm.co.il/sitecode/guitar.jpg" alt="Guitar" style="border: 2px solid black;"/></p>
<p>On windows, assuming imports are free:</p>
<div class="syntax_hilite">
<div id="python-4">
<div class="python"><span style="color: #00007f;font-weight:bold;">import</span> <span style="color: #dc143c;">winsound</span><br />
<span style="color: #dc143c;">winsound</span>.<span style="color: #000000;">Beep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">220</span>*<span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span>**<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>/<span style="color: #ff4500;">12</span>.<span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>**<span style="color: #ff4500;">7</span><span style="color: black;">&#41;</span>, <span style="color: #ff4500;">2000</span><span style="color: black;">&#41;</span></div>
</div>
</div>
<p></p>
<p>But that's just because I like to tune to E. If you prefer a more "natural looking" note, you can use A:</p>
<div class="syntax_hilite">
<div id="python-5">
<div class="python"><span style="color: #dc143c;">winsound</span>.<span style="color: #000000;">Beep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">110</span>, <span style="color: #ff4500;">1000</span><span style="color: black;">&#41;</span></div>
</div>
</div>
<p></p>
<p>But why choose at all when you can go for all of them?</p>
<div class="syntax_hilite">
<div id="python-6">
<div class="python"><span style="color: black;">&#91;</span><span style="color: #dc143c;">winsound</span>.<span style="color: #000000;">Beep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">220</span>*<span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span>**<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>/<span style="color: #ff4500;">12</span>.<span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>**i<span style="color: black;">&#41;</span>, <span style="color: #ff4500;">500</span><span style="color: black;">&#41;</span> <span style="color: #00007f;font-weight:bold;">for</span> i <span style="color: #00007f;font-weight:bold;">in</span> <span style="color: black;">&#91;</span><span style="color: #ff4500;">7</span>, <span style="color: #ff4500;">2</span>, -<span style="color: #ff4500;">2</span>, -<span style="color: #ff4500;">7</span>, -<span style="color: #ff4500;">12</span>, -<span style="color: #ff4500;">17</span><span style="color: black;">&#93;</span><span style="color: black;">&#93;</span></div>
</div>
</div>
<p></p>
<p><small>Image by <a href="http://www.flickr.com/photos/keela84/8075445/">Keela84</a></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/index.php/programming/python/one-liner-guitar-tuner-in-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Visualizing Data Using the Hilbert Curve</title>
		<link>http://www.algorithm.co.il/blogs/index.php/programming/python/visualizing-data-using-the-hilbert-curve/</link>
		<comments>http://www.algorithm.co.il/blogs/index.php/programming/python/visualizing-data-using-the-hilbert-curve/#comments</comments>
		<pubDate>Sat, 17 Apr 2010 06:57:30 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Fractals]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[hilbert curve]]></category>
		<category><![CDATA[PIL]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=525</guid>
		<description><![CDATA[Some time ago, a coworker asked me to help him visualize some data. He had a very long series (many millions) of data points, and he thought that plotting a pixel for each one would visualize it well, so he asked for my help.
I installed Python &#038; PIL on his machine, and not too long [...]]]></description>
			<content:encoded><![CDATA[<p>Some time ago, a coworker asked me to help him visualize some data. He had a very long series (many millions) of data points, and he thought that plotting a pixel for each one would visualize it well, so he asked for my help.<br />
I installed Python &#038; PIL on his machine, and not too long after, he had the image plotted. The script looked something like:</p>
<div class="syntax_hilite">
<div id="python-9">
<div class="python">data_points = get_data_points<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
n =&nbsp; <span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #008000;">len</span><span style="color: black;">&#40;</span>data_points<span style="color: black;">&#41;</span>**<span style="color: #ff4500;">0</span>.<span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span> + <span style="color: #ff4500;">0</span>.<span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span></p>
<p>image = Image<span style="color: black;">&#40;</span><span style="color: #483d8b;">'1'</span>, <span style="color: black;">&#40;</span>n, n<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><br />
<span style="color: #00007f;font-weight:bold;">for</span> idx, pt <span style="color: #00007f;font-weight:bold;">in</span> <span style="color: #008000;">enumerate</span><span style="color: black;">&#40;</span>data_points<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; image.<span style="color: #000000;">putpixel</span><span style="color: black;">&#40;</span>pt, <span style="color: black;">&#40;</span>idx/n, idx%n<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><br />
image.<span style="color: #000000;">save</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'bla.png'</span>, <span style="color: #483d8b;">'png'</span><span style="color: black;">&#41;</span></div>
</div>
</div>
<p>
Easy enough to do. Well, easy enough if you have enough memory to handle very large data sets. Luckily enough, we had just enough memory for this script &#038; data series, and we were happy. The image was generated, and everything worked fine.</p>
<p>Still, we wanted to improve on that. One problem with this visualization is that two horizontally adjacent pixels don’t have anything to do with each other. Remembering xkcd’s "<a href="http://xkcd.com/195/">Map of the Internet</a>", I decided to use the <a href="http://en.wikipedia.org/wiki/Hilbert_curve">Hilbert Curve</a>. I started with wikipedia's version of the code for the Python turtle and changed it to generate a string of instructions of where to put pixels. On the way I improved the time complexity by changing it to have only two recursion calls instead of four. (It can probably be taken down to one by the way, I leave that as a challenge to the reader :)</p>
<p>Unfortunately, at this point we didn’t have enough memory to hold all of those instructions, so I changed it into a generator. Now it was too slow. I cached the lower levels of the recursion, and now it worked in reasonable time (about 3-5 minutes), with reasonable memory requirements (no OutOfMemory exceptions). Of course, I'm skipping a bit of exceptions and debugging along the way. Still, it was relatively straightforward.</p>
<p>Writing the generator wasn't enough - there were still pixels to draw! It took a few more minutes to write a simple "turtle", that walks the generated hilbert curve.<br />
Now, we were ready:</p>
<div class="syntax_hilite">
<div id="python-10">
<div class="python">hilbert = Hilbert<span style="color: black;">&#40;</span><span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">math</span>.<span style="color: #000000;">log</span><span style="color: black;">&#40;</span><span style="color: #008000;">len</span><span style="color: black;">&#40;</span>data_points<span style="color: black;">&#41;</span>, <span style="color: #ff4500;">4</span><span style="color: black;">&#41;</span> + <span style="color: #ff4500;">0</span>.<span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><br />
<span style="color: #00007f;font-weight:bold;">for</span> pt <span style="color: #00007f;font-weight:bold;">in</span> data_points:<br />
&nbsp; &nbsp; x,y = hilbert.<span style="color: #000000;">next</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; image.<span style="color: #000000;">putpixel</span><span style="color: black;">&#40;</span>pt, <span style="color: black;">&#40;</span>x,y<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></div>
</div>
</div>
<p>
A few minutes later, the image was generated. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/index.php/programming/python/visualizing-data-using-the-hilbert-curve/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Fuzz-Testing With Nose</title>
		<link>http://www.algorithm.co.il/blogs/index.php/programming/python/fuzz-testing-with-nose/</link>
		<comments>http://www.algorithm.co.il/blogs/index.php/programming/python/fuzz-testing-with-nose/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 07:49:01 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[fuzzing]]></category>
		<category><![CDATA[nose]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=587</guid>
		<description><![CDATA[A few days ago, I found a in my website, plnnr.com. The bug was in a new feature I added to the algorithm. The first thing I did was write a small unit-test to reproduce the bug. With that unit-test in hand, I then worked to fix the bug, and got this unit-test to pass. [...]]]></description>
			<content:encoded><![CDATA[<p>A few days ago, I found a in my website, <a href="http://plnnr.com">plnnr.com</a>. The bug was in a new feature I added to the algorithm. The first thing I did was write a small unit-test to reproduce the bug. With that unit-test in hand, I then worked to fix the bug, and got this unit-test to pass. </p>
<p>As I previously persumed this feature to be (relatively :) bug free, I decided that more testing was in order. This time however, a single test-case would not be enough - I needed to make sure that the trip-generation algorithm works in many cases. Enter <a href="http://en.wikipedia.org/wiki/Fuzz_testing">fuzzing</a>.</p>
<p>Plnnr.com generates trips according to trip preferences. Why not generate the trip preferences with a fuzzer, and then check if the planning algorithm chokes on them? While fuzzing is usually used to generate invalid input with the goal of causing the program to crash, in this case I'm generating valid input with the goal of causing the planning algorithm to fail.</p>
<p>Usually fuzzing is done with one of two techniques - exhaustive fuzzing, that goes systematically (possibly selectively) over the input space and random fuzzing, which picks inputs at random - or "somewhat" randomly. In my case, the input space consists of "world data" - locations of attractions, restaurants, etc, and trip preferences - intensity, required attractions, and so on. Since the input space is so large and "unstructured", I found it much easier to go with random fuzzing. </p>
<p>In each test-case, I will generate a "random world", and random trip preferences for that world.<br />
Here is some sample code that shows how this might look:</p>
<div class="syntax_hilite">
<div id="python-15">
<div class="python">trip_prefs.<span style="color: #000000;">num_days</span> = <span style="color: #dc143c;">random</span>.<span style="color: #000000;">randint</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span><br />
trip_prefs.<span style="color: #000000;">intensity</span> = <span style="color: #dc143c;">random</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span><br />
<span style="color: #00007f;font-weight:bold;">if</span> randbit<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; trip_prefs.<span style="color: #000000;">schedule_lunch</span> = <span style="color: #008000;">True</span></div>
</div>
</div>
<p></p>
<p>Where randbit is defined like so:</p>
<div class="syntax_hilite">
<div id="python-16">
<div class="python"><span style="color: #00007f;font-weight:bold;">def</span> randbit<span style="color: black;">&#40;</span>prob = <span style="color: #ff4500;">0</span>.<span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">return</span> <span style="color: #dc143c;">random</span>.<span style="color: #dc143c;">random</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> &lt; prob</div>
</div>
</div>
<p></p>
<p>This is all very well, but tests need to be reproducible. If a fuzzer-generated test case fails and I can't recreate it to analyze the error and later verify that it is fixed, it isn't of much use. To solve this issue, the input generation function receives some value, and sets the random seed with this parameter. Now, generating test cases is just a matter of generating a sequence of random values. Here is my code to do that:</p>
<div class="syntax_hilite">
<div id="python-17">
<div class="python"><span style="color: #00007f;font-weight:bold;">class</span> FuzzTestBase<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; __test__ = <span style="color: #008000;">False</span><br />
&nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">def</span> run_single_fuzz<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, random_seed<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">pass</span><br />
&nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">def</span> fuzz_test<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #dc143c;">random</span>.<span style="color: #000000;">seed</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; random_seeds = <span style="color: black;">&#91;</span><span style="color: #008000;">str</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">random</span>.<span style="color: #dc143c;">random</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> <span style="color: #00007f;font-weight:bold;">for</span> i <span style="color: #00007f;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span>NUM_FUZZ_TESTS<span style="color: black;">&#41;</span><span style="color: black;">&#93;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">for</span> seed <span style="color: #00007f;font-weight:bold;">in</span> random_seeds:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">yield</span> <span style="color: #008000;">self</span>.<span style="color: #000000;">run_single_fuzz</span>, seed</div>
</div>
</div>
<p></p>
<p>FuzzTestBase is a base-class for actual test classes. Each test class just needs to define its own version of run_single_fuzz, and in it call random.seed(random_seed) and log random_seed.</p>
<p>This code uses <a href="http://somethingaboutorange.com/mrl/projects/nose/0.11.3/">nose</a>'s ability to test generators: it assumes that a test generator yields test functions and their parameters.</p>
<p>A few interesting issues:<br />
* I generate the random seeds beforehand, so that calling random.seed() in the actual test case doesn't affect the seed sequence.<br />
* Originally I used just random.random() as a seed instead of str(random.random()). The problem with that is that this way it's not reproducible. random.random() returns a floating point value x, for which usually x != eval(str(x)):</p>
<div class="syntax_hilite">
<div id="python-18">
<div class="python">In <span style="color: black;">&#91;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#93;</span>: x = <span style="color: #dc143c;">random</span>.<span style="color: #dc143c;">random</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
In <span style="color: black;">&#91;</span><span style="color: #ff4500;">11</span><span style="color: black;">&#93;</span>: x == <span style="color: #008000;">eval</span><span style="color: black;">&#40;</span><span style="color: #008000;">str</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><br />
Out<span style="color: black;">&#91;</span><span style="color: #ff4500;">11</span><span style="color: black;">&#93;</span>: <span style="color: #008000;">False</span></div>
</div>
</div>
<p></p>
<p>Even though x == eval(repr(x)) for that case, there's still room for error. Unlike floating point numbers, it's harder to go wrong with string equality. So str(random.random()) is just a cheap way to generate random strings.</p>
<p>I'd recommend that if your testing mostly consists of selected test cases based on what you think is possible user behavior, you might want to add some fuzzed inputs. I originally started the fuzz-testing described in this blog-post to better test for a specific bug. After adding the fuzz-testing, I found another bug I didn't know was there. This just goes to show how useful fuzzing is as a testing tool. The fact that it's so easy to implement is just a bonus.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/index.php/programming/python/fuzz-testing-with-nose/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Pyweb-il Presentation on Optimization Slides</title>
		<link>http://www.algorithm.co.il/blogs/index.php/programming/python/pyweb-il-oresentation-on-optimization-slides/</link>
		<comments>http://www.algorithm.co.il/blogs/index.php/programming/python/pyweb-il-oresentation-on-optimization-slides/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 18:31:50 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Optimization]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[presentation slides]]></category>
		<category><![CDATA[pyweb-il]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=570</guid>
		<description><![CDATA[Last Monday I gave a presentation in pywebil on optimization, that's loosely based on my blog post on the same subject. Here are the slides for that presentation.
]]></description>
			<content:encoded><![CDATA[<p>Last Monday I gave a presentation in <a href="http://groups.google.com/group/pyweb-il">pywebil</a> on optimization, that's loosely based on my <a href="http://www.algorithm.co.il/blogs/index.php/programming/python/10-python-optimization-tips-and-issues/">blog post on the same subject</a>. Here are the <a href="http://www.algorithm.co.il/sitecode/optimization.pdf">slides for that presentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/index.php/programming/python/pyweb-il-oresentation-on-optimization-slides/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple SQLObject DB Migration how-to</title>
		<link>http://www.algorithm.co.il/blogs/index.php/programming/python/simple-sqlobject-db-migration-how-to/</link>
		<comments>http://www.algorithm.co.il/blogs/index.php/programming/python/simple-sqlobject-db-migration-how-to/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 05:50:58 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[database migration]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[sqlobject]]></category>
		<category><![CDATA[turbogears]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=507</guid>
		<description><![CDATA[I've been using sqlobject for plnnr.com for quite some time now. So far my experience with it has been positive. Although I'll probably change ORM when I move to django, for now it stays. While it stays, I need to be able to upgrade my schema to add features.
SQLObject already has a tool for the [...]]]></description>
			<content:encoded><![CDATA[<p>I've been using sqlobject for <a href="http://plnnr.com">plnnr.com</a> for quite some time now. So far my experience with it has been positive. Although I'll probably change ORM when I move to django, for now it stays. While it stays, I need to be able to upgrade my schema to add features.<br />
SQLObject already has a tool for the job, sqlobject-admin. There are instructions on how to use it, but I found them unsatisfactory.<br />
(By the way, both django's ORM and sqlalchemy also have tools for that, django-south and sqlalchemy-migrate respectively.)</p>
<p>So here is how I use sqlobject-admin to do migrations. Note that if you're using turbogears 1.0, you would probably be using tg-admin. In that case, bear in mind that tg-admin just simplifies the job for you by adding various standard parameters, but apart from that, the idea stays the same.<br />
Notes:<br />
* I wrote these instructions on a windows machine. On linux machines it should be almost the same, but might require tweaking.<br />
* I used a specific db URI in the examples. You can change it to whatever you want.<br />
* I once had to tweak the main sqlobject-admin file to add the current dir to sys.path. YMMV.</p>
<p><strong>1. Example project:</strong><br />
Let's setup a project that uses sqlobject. We'll create a single file, 'main.py' with the following content:</p>
<div class="syntax_hilite">
<div id="python-22">
<div class="python"><span style="color: #00007f;font-weight:bold;">import</span> sqlobject</p>
<p>sqlobject.<span style="color: #000000;">sqlhub</span>.<span style="color: #000000;">processConnection</span> = sqlobject.<span style="color: #000000;">connectionForURI</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'sqlite:/D|/work/sotest/sotest.sqlite'</span><span style="color: black;">&#41;</span></p>
<p><span style="color: #00007f;font-weight:bold;">class</span> MyThing<span style="color: black;">&#40;</span>sqlobject.<span style="color: #000000;">SQLObject</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; bla = sqlobject.<span style="color: #000000;">StringCol</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></div>
</div>
</div>
<p></p>
<p>This is about as simple as I could get it with sqlobject.</p>
<p><strong>2. Starting to use sqlobject-admin</strong><br />
Sqlobject-admin has quite a bit of bureaucracy to go through before you get everything to work right. For a simple project, I cheat (i.e. fake an egg :), and do the following:<br />
a. Create a directory in your project called sqlobject-history<br />
b. If your project name is sotest, create a directory inside your project called sotest.egg-info<br />
c. Inside that dir create a file called sqlobject.txt<br />
d. Inside that file write:</p>
<div class="syntax_hilite">
<div id="python-23">
<div class="python">db_module=main<br />
history_dir=$base/sqlobject-history</div>
</div>
</div>
<p></p>
<p>(note that the main here is the name of the module we created earlier).</p>
<p><strong>3. Start using sqlobject-admin</strong><br />
This will be the workflow with sqlobject-admin:<br />
1. Have the creation sql for the current code version.<br />
2. Update your code<br />
3. Generate the creation sql for the new code version, *without updating the db*<br />
4. Create an upgrade script using the diff between the versions<br />
5. Use the upgrade script.</p>
<p>More specifically:<br />
1. First time - do:</p>
<blockquote><p>sqlobject-admin record --egg=sotest -c sqlite:/D|/work/sotest/sotest.sqlite</p></blockquote>
<p>2. To see that everything works, do:</p>
<blockquote><p>sqlobject-admin list --egg=sotest -c sqlite:/D|/work/sotest/sotest.sqlite</p></blockquote>
<p>and:</p>
<blockquote><p>sqlobject-admin status --egg=sotest -c sqlite:/D|/work/sotest/sotest.sqlite</p></blockquote>
<p>3. Update your database definition (in the Python file). For example, change the contents of main.py to:</p>
<div class="syntax_hilite">
<div id="python-24">
<div class="python"><span style="color: #00007f;font-weight:bold;">import</span> sqlobject</p>
<p>sqlobject.<span style="color: #000000;">sqlhub</span>.<span style="color: #000000;">processConnection</span> = sqlobject.<span style="color: #000000;">connectionForURI</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'sqlite:/D|/work/sotest/sotest.sqlite'</span><span style="color: black;">&#41;</span></p>
<p><span style="color: #00007f;font-weight:bold;">class</span> MyThing<span style="color: black;">&#40;</span>sqlobject.<span style="color: #000000;">SQLObject</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; bla = sqlobject.<span style="color: #000000;">StringCol</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; bla2 = sqlobject.<span style="color: #000000;">StringCol</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></div>
</div>
</div>
<p></p>
<p>4. Here is the critical part. Do</p>
<blockquote><p>sqlobject-admin record --egg=sotest -c sqlite:/D|/work/sotest/sotest.sqlite --no-db-record</p></blockquote>
<p>In the sqlobject-history directory there should be now two subdirectories, for each version. Let's call the old version X and the new version Y. In the old version directory create a file:<br />
upgrade_sqlite_Y.sql (where Y is the new version's name).<br />
In this file, write down the sql to add the bla2 column to the MyThing table. You can use the creation sql commands in the respective versions' directories to write it.</p>
<p>(note: if we used --edit we would get an editor opened, and if the edited file has any content when you close it, it will be saved as the upgrade script. I don't like using this method. Note that if you're on windows you'll have to fix sqlobject-admin to open your editor, as the command it uses works only on linux machines.)</p>
<p>5. run<br />
<blockquote>sqlobject-admin upgrade --egg=sotest -c sqlite:/D|/work/sotest/sotest.sqlite</p></blockquote>
<p>6. Make sure everything is OK with sqlobject-admin status.</p>
<p><strong>3. After using the upgrade script</strong><br />
You can use the same upgrade script for other instances of your project. Just make sure that you have the versions numbers correct, and the first version recorded in the database.</p>
<p>I hope this will be useful for someone using sqlobject, I know I needed this kind of how-to. If you have any questions, feel free to ask them in comments below.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/index.php/programming/python/simple-sqlobject-db-migration-how-to/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The mathematics behind the solution for Challenge No. 5</title>
		<link>http://www.algorithm.co.il/blogs/index.php/programming/python/the-mathematics-behind-the-solution-for-challenge-no-5/</link>
		<comments>http://www.algorithm.co.il/blogs/index.php/programming/python/the-mathematics-behind-the-solution-for-challenge-no-5/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:49:15 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Challenges]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[computer science]]></category>
		<category><![CDATA[base systems]]></category>
		<category><![CDATA[factorial]]></category>
		<category><![CDATA[Knuth]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[permutations]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=500</guid>
		<description><![CDATA[If you take a look at the various solutions people proposed for the last challenge of generating a specific permutation, you'll see that they are very similar. Most of them are based on some form of div-mod usage. The reason this is so, is because all of these solutions are using the Factorial Base.
What does [...]]]></description>
			<content:encoded><![CDATA[<p>If you take a look at the various solutions people proposed for the <a href="http://www.algorithm.co.il/blogs/index.php/programming/small-programming-challenge-no-5-generating-a-permutation/">last challenge of generating a specific permutation</a>, you'll see that they are very similar. Most of them are based on some form of div-mod usage. The reason this is so, is because all of these solutions are using the <a href="http://en.wikipedia.org/wiki/Factorial_base">Factorial Base</a>.</p>
<p>What does that mean?<br />
Note that we usually encounter div-mods when we want to find the representation of a number in a certain base. That should already pique your interest. Now consider that a base's digits need not have the same weight. For example, consider how we count the number of seconds since the start of the week:</p>
<p>seconds of the last minute, A (at most 60-1)<br />
minutes of the last hour, B (at most 60-1)<br />
hours of the last day, C (at most (24-1)<br />
days of the last week, D (at most 7-1)</p>
<p>So given A, B, C, D, we would say that the number of seconds is:<br />
A + 60*B + 24*C + 7*D. This certainly looks like a base transformation. To go back, we would use divmod.</p>
<p>The factorial base is just the same, with the numbers n, n-1, ... 1. Note that in the factorial base, you can only represent a finite number of numbers - n!. This should not be surprising - this is what we set out to do in the first place!<br />
The thing that I found really amazing about this is that all the people to whom I posed this challenge came up with almost the same "way" of solving it. </p>
<p>Other interesting curiosities regarding bases can be found in Knuth's book, "The Art of Computer Programming", volume 2, Section 4.1. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/index.php/programming/python/the-mathematics-behind-the-solution-for-challenge-no-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>And now for something completely different</title>
		<link>http://www.algorithm.co.il/blogs/index.php/programming/python/and-now-for-something-completely-different/</link>
		<comments>http://www.algorithm.co.il/blogs/index.php/programming/python/and-now-for-something-completely-different/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 18:28:42 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Humour]]></category>
		<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[clip]]></category>
		<category><![CDATA[humor]]></category>
		<category><![CDATA[python zen]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=484</guid>
		<description><![CDATA[My friend Yuval whom you might already know from the comments here, apparently composed music for the Python Zen. It made me laugh today, and as it's been a long day, I thought it's worth sharing here. Especially as it is Python related.

]]></description>
			<content:encoded><![CDATA[<p>My friend <a href="http://uberpython.wordpress.com/">Yuval</a> whom you might already know from the comments here, apparently composed music for the <a href="http://www.python.org/dev/peps/pep-0020/">Python Zen</a>. It made me laugh today, and as it's been a long day, I thought it's worth sharing here. Especially as it is Python related.</p>
<p><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/kYB72Qa6F9I&#038;hl=en&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/kYB72Qa6F9I&#038;hl=en&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/index.php/programming/python/and-now-for-something-completely-different/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Leaky method references</title>
		<link>http://www.algorithm.co.il/blogs/index.php/programming/python/leaky-method-references/</link>
		<comments>http://www.algorithm.co.il/blogs/index.php/programming/python/leaky-method-references/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 08:39:25 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Bugs]]></category>
		<category><![CDATA[Gotcha]]></category>
		<category><![CDATA[memory leak]]></category>
		<category><![CDATA[__del__]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=472</guid>
		<description><![CDATA[After reading my last post regarding __del__, you should know that __del__ + reference cycle = leak.
Let's say that you do need to use __del__, so you decide to avoid reference cycles. You write your code in such a way as to use the minimum necessary cycles, and for the ones that remain you use [...]]]></description>
			<content:encoded><![CDATA[<p>After reading my last post <a href="http://www.algorithm.co.il/blogs/index.php/programming/python/python-gotchas-no-2-garbage-collection-oddities/">regarding __del__</a>, you should know that __del__ + reference cycle = leak.<br />
Let's say that you do need to use __del__, so you decide to avoid reference cycles. You write your code in such a way as to use the minimum necessary cycles, and for the ones that remain you use the weakref module.</p>
<p>You might still have cycles where you don't expect it - in references to methods.<br />
Consider the following piece of code. Can you spot the reference cycle?</p>
<div class="syntax_hilite">
<div id="python-27">
<div class="python"><span style="color: #00007f;font-weight:bold;">class</span> A<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">def</span> f<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">return</span></p>
<p>a = A<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
a.<span style="color: #000000;">g</span> = a.<span style="color: #000000;">f</span></div>
</div>
</div>
<p></p>
<p>This code has the following reference cycle: a -> a.g -> a.f -> a.<br />
How come?<br />
When you call a.f like so: "a.f()" <strong>two</strong> things happen:<br />
1. A.f is bounded to a<br />
2. The bounded A.f is called with the first parameter getting the bounded value.</p>
<p>You may consider that "a.f" is syntactic sugar for the partial function application, A.f gets a as a first argument but doesn't get called yet.</p>
<p>When you use "a.g = a.f" what actually happens is a holding a reference to a bounded method, which holds a reference to a.</p>
<p>An idiom that uses these cycles is implementing state machines. Consider the following example code:</p>
<div class="syntax_hilite">
<div id="python-28">
<div class="python"><span style="color: #00007f;font-weight:bold;">class</span> MyMachine<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: #000000;">next_func</span> = <span style="color: #008000;">self</span>.<span style="color: #000000;">state_a</span><br />
&nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">def</span> run<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #008000;">input</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">for</span> x <span style="color: #00007f;font-weight:bold;">in</span> <span style="color: #008000;">input</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: #000000;">next_func</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">def</span> state_a<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, value<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">print</span> <span style="color: #483d8b;">'a: '</span>, value<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: #000000;">next_func</span> = <span style="color: #008000;">self</span>.<span style="color: #000000;">state_b</span><br />
&nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">def</span> state_b<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, value<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">print</span> <span style="color: #483d8b;">'b: '</span>, value<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: #000000;">next_func</span> = <span style="color: #008000;">self</span>.<span style="color: #000000;">state_a</span></div>
</div>
</div>
<p></p>
<p>Of course, my code was a bit more complicated than that, but the basic idea remains. (My code usually created some kind of function table in __init__ used to lookup the next function, and lookups happened outside "state functions"). I've seen many state machine recipes include method references - and rightly so. It's a clear and easy way to code a state machine. (For example, <a href="http://code.activestate.com/recipes/574430/">this state machine recipe</a>).<br />
Be careful though - once you add __del__ to these simple recipes you might end up with a memory leak. </p>
<p>Short note: I was going to publish this post a few days ago, but <a href="http://www.kylev.com/2009/11/03/finding-my-first-python-reference-cycle/">kylev</a> beat me to it. This just goes to show that other people encountered this kind of cycle.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/index.php/programming/python/leaky-method-references/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python Gotchas No. 2: Garbage Collection Oddities</title>
		<link>http://www.algorithm.co.il/blogs/index.php/programming/python/python-gotchas-no-2-garbage-collection-oddities/</link>
		<comments>http://www.algorithm.co.il/blogs/index.php/programming/python/python-gotchas-no-2-garbage-collection-oddities/#comments</comments>
		<pubDate>Fri, 30 Oct 2009 13:10:22 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[gc]]></category>
		<category><![CDATA[Gotcha]]></category>
		<category><![CDATA[__del__]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=462</guid>
		<description><![CDATA[Python is a garbage collected language. The garbage collector will collect orphaned objects. These are objects that have no references.
If an object has a __del__ method, it will be called when that object is collected. Note however, that there are no guarantees as to when this will take place. This means that while you should [...]]]></description>
			<content:encoded><![CDATA[<p>Python is a garbage collected language. The garbage collector will collect orphaned objects. These are objects that have no references.<br />
If an object has a __del__ method, it will be called when that object is collected. Note however, that there are no guarantees as to when this will take place. This means that while you should release all owned resources in the __del__ method, you should not depend on it to release these resources when the object "goes out of scope" as in C++.<br />
Specifically note that del x <strong>does not</strong> call x's __del__ method, just removes this specific reference to x.<br />
To be explicit about resource management, call the appropriate function yourself in the flow of your program, or better yet, use try-finally or the with statement. (For more information about those, see my presentation about <a href="http://www.algorithm.co.il/blogs/index.php/programming/python/pyweb-il-presentation-advanced-subjects-in-python/">advanced python subjects</a>).</p>
<p>There is another interesting caveat regarding Python's gc. Consider the following code:</p>
<div class="syntax_hilite">
<div id="python-30">
<div class="python"><span style="color: #00007f;font-weight:bold;">class</span> A<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #00007f;font-weight:bold;">pass</span></p>
<p>a = A<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
b = A<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
a.<span style="color: #000000;">x</span> = b<br />
b.<span style="color: #000000;">x</span> = a<br />
<span style="color: #00007f;font-weight:bold;">del</span> a<br />
<span style="color: #00007f;font-weight:bold;">del</span> b</div>
</div>
</div>
<p></p>
<p>Did a and b lose their references? Well, they didn't. They're still pointing at each other, creating a <strong>reference cycle</strong>. Happily, Python's garbage collector can still handle those. However, it won't be able to handle reference cycles if at least one object in the cycle has a __del__ method.<br />
To understand why, consider the above example, only this time assume A has a __del__ method that calls self.x.release().</p>
<p>Now, which __del__ method should be called first? if it is called, is the other one still valid? Python refuses the temptation to guess, and leaves the cycle be, creating a memory (or resource) leak.<br />
The solution?<br />
1. Avoid data structures with reference cycles. For instance, there are very few instances where you'd need a <a href="http://www.algorithm.co.il/blogs/index.php/programming/python/lru-cache-solution-a-case-for-linked-lists-in-python/">doubly linked list</a> :)<br />
2. If you do need reference cycles, consider using the <a href="http://www.python.org/doc/2.6/library/weakref.html#module-weakref">weakref module</a>, which allows you to create references that "don't count" in the eyes of the gc.</p>
<p>Further reading material:<br />
1. <a href="http://docs.python.org/reference/datamodel.html#object.__del__">The __del__ method</a>.<br />
2. <a href="http://docs.python.org/library/gc.html#module-gc">The gc (garbage collector) module</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/index.php/programming/python/python-gotchas-no-2-garbage-collection-oddities/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PyWeb-IL presentation: Advanced subjects in Python</title>
		<link>http://www.algorithm.co.il/blogs/index.php/programming/python/pyweb-il-presentation-advanced-subjects-in-python/</link>
		<comments>http://www.algorithm.co.il/blogs/index.php/programming/python/pyweb-il-presentation-advanced-subjects-in-python/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 19:47:49 +0000</pubDate>
		<dc:creator>lorg</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Teaching Programming]]></category>

		<guid isPermaLink="false">http://www.algorithm.co.il/blogs/?p=457</guid>
		<description><![CDATA[Yesterday I gave a presentation at PyWeb-IL, which took place at Google's offices in Tel-Aviv. The presentation went really well, and interested many people.
Here are the slides for the presentation, "Advanced Python Subjects".
]]></description>
			<content:encoded><![CDATA[<p>Yesterday I gave a presentation at PyWeb-IL, which took place at Google's offices in Tel-Aviv. The presentation went really well, and interested many people.</p>
<p>Here are the slides for the presentation, <a href="http://www.algorithm.co.il/sitecode/advanced_python_subjects.pdf">"Advanced Python Subjects"</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.algorithm.co.il/blogs/index.php/programming/python/pyweb-il-presentation-advanced-subjects-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
