<?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>Dev-Picayune</title>
	<atom:link href="http://www.devpicayune.com/feed" rel="self" type="application/rss+xml" />
	<link>http://www.devpicayune.com</link>
	<description>picayune: of little value or importance</description>
	<lastBuildDate>Fri, 23 Oct 2009 19:00:36 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>From lists to generators</title>
		<link>http://www.devpicayune.com/entry/from-lists-to-generators</link>
		<comments>http://www.devpicayune.com/entry/from-lists-to-generators#comments</comments>
		<pubDate>Thu, 09 Jul 2009 22:00:30 +0000</pubDate>
		<dc:creator>Brandon Corfman</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[generators]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/?p=196</guid>
		<description><![CDATA[I was working on a section of my Checkers game code a few days ago. It looked like this:

class Checkerboard&#40;object&#41;:
   def legal_moves&#40;self, state&#41;:
	return state.captures or state.moves

The behavior above mirrors the standard Checkers rule that if you have a capture, you must take it &#8212; otherwise, you can make a regular move. In my [...]]]></description>
			<content:encoded><![CDATA[<p>I was working on a section of my Checkers game code a few days ago. It looked like this:</p>

<div class="wp_syntax"><div class="code"><pre class="python"><span style="color: #ff7700;font-weight:bold;">class</span> Checkerboard<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
   <span style="color: #ff7700;font-weight:bold;">def</span> legal_moves<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, state<span style="color: black;">&#41;</span>:
	<span style="color: #ff7700;font-weight:bold;">return</span> state.<span style="color: black;">captures</span> <span style="color: #ff7700;font-weight:bold;">or</span> state.<span style="color: black;">moves</span></pre></div></div>

<p>The behavior above mirrors the standard Checkers rule that if you have a capture, you must take it &#8212; otherwise, you can make a regular move. In my code, both <code>state.captures</code> and <code>state.moves</code> are properties that return Python lists. Since an empty list evaluates to <code>False</code> in an <code>or</code> statement, if <code>state.captures</code> is empty, then the <code>return</code> statement automatically uses <code>state.moves</code> list instead.</p>
<p>Now I was trying to make the <code>legal_moves</code> method work a bit faster and use less memory, so I switched to generators instead. Oops &#8230; now the code above fails since <code>state.captures</code> and <code>state.moves</code> now return generator objects. The <code>legal_moves</code> method above doesn&#8217;t work because <code>state.captures</code> is always a valid object instance and it always evaluates to <code>True</code> in the <code>or</code> statement &#8212; even when there are no actual captures available.</p>
<p>It took some thought to come up with an equivalent behavior for generator objects. In the new version, <code>legal_moves</code> becomes a wrapper method that returns one generator object or the other based on whether the first generator object yields at least one item.</p>

<div class="wp_syntax"><div class="code"><pre class="python"><span style="color: #ff7700;font-weight:bold;">class</span> Checkerboard<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
   <span style="color: #ff7700;font-weight:bold;">def</span> legal_moves<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, state<span style="color: black;">&#41;</span>:
      <span style="color: #ff7700;font-weight:bold;">return</span> state.<span style="color: black;">captures</span> <span style="color: #ff7700;font-weight:bold;">if</span> state.<span style="color: black;">captures</span>.<span style="color: black;">next</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">else</span> state.<span style="color: black;">moves</span></pre></div></div>

<p>It&#8217;s not as elegant as the version using lists, but it works.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/from-lists-to-generators/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Komodo and Django and Ubuntu 9.04</title>
		<link>http://www.devpicayune.com/entry/komodo-and-django-and-ubuntu-904</link>
		<comments>http://www.devpicayune.com/entry/komodo-and-django-and-ubuntu-904#comments</comments>
		<pubDate>Sun, 31 May 2009 19:16:59 +0000</pubDate>
		<dc:creator>ScW</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[komodo]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/?p=194</guid>
		<description><![CDATA[Lately, I&#8217;ve found myself switching from Wing IDE to Komodo IDE for my Python work. One of the major reasons for this has been my switch to using a Mac at work. While Wing runs on the Mac, it&#8217;s really an X11 app and doesn&#8217;t have the full Mac&#8217;y feel that Komodo has. Another reason, [...]]]></description>
			<content:encoded><![CDATA[<p>Lately, I&#8217;ve found myself switching from Wing IDE to Komodo IDE for my Python work. One of the major reasons for this has been my switch to using a Mac at work. While Wing runs on the Mac, it&#8217;s really an X11 app and doesn&#8217;t have the full Mac&#8217;y feel that Komodo has. Another reason, is that while in the past, Komodo&#8217;s code completion was &#8220;less&#8221; it&#8217;s now gotten a lot better and while still not up to the excellent standard of Wing, it&#8217;s pretty good now.</p>
<p>So for work at home, I figured I&#8217;d fully make the switch as well. That&#8217;s when I found an issue. While I had managed to get my Mac code completing well for my django app&#8217;s, my 9.04 ubuntu box at home wasn&#8217;t running so well. Just trying to code complete the django models object didn&#8217;t work.</p>
<p>After trying everything I&#8217;d seen via googling, I found that adding the following directories to the additional directories import seemed to work:</p>
<p>/usr/local/lib/python2.6/dist-packages</p>
<p>/usr/local/lib/python2.6/site-packages</p>
<p>I&#8217;m sure I&#8217;ll end up adding more directories to make it all work right&#8230; but these fixed the basic django code completion issues. Just thought I&#8217;d post this in case I forgot what I did.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/komodo-and-django-and-ubuntu-904/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building Python 2.6 executables for Windows</title>
		<link>http://www.devpicayune.com/entry/building-python-26-executables-for-windows</link>
		<comments>http://www.devpicayune.com/entry/building-python-26-executables-for-windows#comments</comments>
		<pubDate>Sat, 21 Mar 2009 00:43:46 +0000</pubDate>
		<dc:creator>Brandon Corfman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[deployment]]></category>
		<category><![CDATA[executables]]></category>
		<category><![CDATA[gui2exe]]></category>
		<category><![CDATA[manifest]]></category>
		<category><![CDATA[py2exe]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[sxs]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[virtualization]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/?p=191</guid>
		<description><![CDATA[I finally made a build of my game, Raven Checkers, on Windows XP. In the process I ran into the same issues as everyone else with Python 2.6 and the new requirement for manifest files. Since Python 2.6 binaries for Windows are now compiled using Visual Studio 2008, a manifest file is required both for [...]]]></description>
			<content:encoded><![CDATA[<p>I finally made a build of my game, <a href="http://raven-checkers.googlecode.com">Raven Checkers</a>, on Windows XP. In the process I ran into the same issues as everyone else with Python 2.6 and the <a href="http://www.velocityreviews.com/forums/t648934-executables-no-longer-executing-on-pcs-without-python-installed.html">new requirement for manifest files</a>. Since Python 2.6 binaries for Windows are now compiled using Visual Studio 2008, a manifest file is required both for your own executable and for the C runtime that Python uses. I was not able to find a simple step-by-step process on how to do this, so here&#8217;s how I do it.</p>
<ol>
<li><em>Make sure that Python 2.6 is installed on your system with the &#8220;Install just for me&#8221; option during setup. </em>This ensures that the DLLs and manifest files that you will need will be placed into the Python26 directory where you can easily locate them later.</li>
<li><em>Build an executable of your program for Windows.</em> I&#8217;m using <a href="http://code.google.com/p/gui2exe/">gui2exe</a> (0.3) and <a href="http://sourceforge.net/projects/py2exe/">py2exe</a> (0.6.9) to make it simple. I set the Bundle Files option to 2, and the Compression option to 0. Why, do you ask? I am unable to get any other combination of options to work properly. If you can, more power to you. I also use the option to create a dist directory called, um, &#8216;dist&#8217;.</li>
<li><em>From the Python26 directory, copy msvcr90.dll, Microsoft.VC90.CRT.manifest, and python.exe.manifest over to your dist folder.</em></li>
<li><em>Rename the python.exe.manifest file to [yourappname].exe.manifest.</em></li>
</ol>
<p>Now you should be able to copy your dist folder over to a clean Windows machine, double-click on your executable and have it start without any side-by-side configuration issues.</p>
<p>By the way, If you don&#8217;t have a clean Windows machine to test on your app on, the easy and free solution is to download <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=28C97D22-6EB8-4A09-A7F7-F6C7A1F000B5&amp;displaylang=en">Microsoft Virtual PC 2007</a> and a <a href="http://www.microsoft.com/Downloads/details.aspx?FamilyID=21eabb90-958f-4b64-b5f1-73d0a413c8ef&amp;displaylang=en">free XP or Vista virtual machine image</a>. Once VPC is installed, you can copy your files to your virtual machine by simply dragging them from your dev machine desktop onto the VPC desktop window.</p>
<p>Here&#8217;s to Windows deployment and testing made (relatively) simple! Hope this saves you some hours of Googling.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/building-python-26-executables-for-windows/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Object pooling in Python</title>
		<link>http://www.devpicayune.com/entry/object-pooling-in-python</link>
		<comments>http://www.devpicayune.com/entry/object-pooling-in-python#comments</comments>
		<pubDate>Thu, 20 Nov 2008 17:37:39 +0000</pubDate>
		<dc:creator>Brandon Corfman</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[oop]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/?p=148</guid>
		<description><![CDATA[This post discusses an object pool design pattern that is applicable in the following scenario:

You have a list of objects whose state is continually updated.
The objects are frequently added or deleted from the list, i.e. have limited lifetimes.
You want to reuse the objects instead, to improve performance or simplify your code.

&#160;
Introduction
When writing my game Asteroid [...]]]></description>
			<content:encoded><![CDATA[<p>This post discusses an object pool design pattern that is applicable in the following scenario:</p>
<ul>
<li>You have a list of objects whose state is continually updated.</li>
<li>The objects are frequently added or deleted from the list, i.e. have limited lifetimes.</li>
<li>You want to reuse the objects instead, to improve performance or simplify your code.</li>
</ul>
<p>&nbsp;</p>
<h2>Introduction</h2>
<p>When writing my game <a href="http://mysite.verizon.net/bcorfman/2007/01/asteroid-smash-released.html" target="_blank">Asteroid Smash</a> using <a href="http://www.python.org">Python</a>, I used lists to keep track of on-screen objects like laser shots and asteroids. These objects all have limited lifetimes (for example, a laser shot that only goes a predetermined distance, or an asteroid that drifts across the screen until it gets destroyed). When it&#8217;s no longer needed, the object then gets deleted from its associated list. Here is a simplified example:</p>

<div class="wp_syntax"><div class="code"><pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">random</span>
&nbsp;
MAX_SHOTS = <span style="color: #ff4500;">5</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Shot<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, lifetime<span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">lifetime</span> = lifetime
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> update<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">lifetime</span> -= <span style="color: #ff4500;">1</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">lifetime</span> &gt; <span style="color: #ff4500;">0</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># create list of Shots with random lifetimes</span>
lst = <span style="color: black;">&#91;</span>Shot<span style="color: black;">&#40;</span><span style="color: #dc143c;">random</span>.<span style="color: black;">randint</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">100</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span>MAX_SHOTS<span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># update loop</span>
<span style="color: #ff7700;font-weight:bold;">while</span> lst:
    delete_lst = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> i, x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">enumerate</span><span style="color: black;">&#40;</span>lst<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> x.<span style="color: black;">update</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>: <span style="color: #808080; font-style: italic;"># decrement object lifetime</span>
            delete_lst.<span style="color: black;">append</span><span style="color: black;">&#40;</span>i<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># delete any objects whose time count is 0</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">reversed</span><span style="color: black;">&#40;</span>delete_lst<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">del</span> lst<span style="color: black;">&#91;</span>i<span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Done!&quot;</span></pre></div></div>

<p>To summarize what&#8217;s going on, a list of 5 <span style="font-family: Courier;">Shot</span> objects gets created, each with random <span style="font-family: Courier;">lifetime</span> values, and added to a list. After that, a loop is started that calls an <span style="font-family: Courier;">update</span> method on each <span style="font-family: Courier;">Shot</span> that decrements its <span style="font-family: Courier;">lifetime</span> variable by 1. (This roughly simulates what would happen during each pass of a typical game loop.) Once the object&#8217;s <span style="font-family: Courier;">lifetime</span> value reaches zero, then the object is added to a delete list. Any objects in the delete list get destroyed after each pass of the update loop.</p>
<p>This code works, but it&#8217;s clumsy. Note all the bookkeeping that&#8217;s necessary. I can&#8217;t delete items while I&#8217;m iterating through the list, or I&#8217;ll invalidate the iterator. This means I have to keep track of the index of which items need to be deleted, and then actually delete them in a second loop. Also, I have to delete the items in reverse order, or I&#8217;ll throw off the indexes and delete the wrong items.</p>
<p>To improve the code, I decided to try list comprehensions to shorten the amount of code in the update loop.</p>

<div class="wp_syntax"><div class="code"><pre class="python"><span style="color: #808080; font-style: italic;"># new update loop with list comp</span>
<span style="color: #ff7700;font-weight:bold;">while</span> lst:
    lst = <span style="color: black;">&#91;</span>x <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> lst <span style="color: #ff7700;font-weight:bold;">if</span> x.<span style="color: black;">update</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span></pre></div></div>

<p>This is much more appealing, single-pass approach. However, the list comprehension, while tidy looking, has a big disadvantage: it constantly creates and destroys a list during each iteration of the loop. This makes it a big problem if we pass around a reference to the list within our program, as the reference is immediately invalidated when the list is recreated. If we need to keep the reference to our list constant, then we have to try another approach.</p>
<p>&nbsp;</p>
<h2>Rethinking the problem</h2>
<p>Perhaps if we want to make a better design, then we need to recast the problem slightly. Notice that once all the objects have a <span style="font-family: Courier;">lifetime</span> count of 0, then they can all be deleted at one time, which is a straightforward problem. This means filtering the list by deleting the objects turns out to be unnecessary; what we want is a way to separate objects that still need to be updated in the list from those that do not. Then, once all of the objects fail the <span style="font-family: Courier;">update</span> call, the entire list can be deleted.</p>
<p>A little-known algorithm in the C++ Standard Template Library (STL) called <span style="font-family: Courier;">partition</span> does the separation of elements mentioned above. Given a sequence, <span style="font-family: Courier;">partition</span> will reorder items in the sequence so that all items that satisfy a certain condition (like an <span style="font-family: Courier;">update</span> call!) precede those that fail the condition. One other great thing about <span style="font-family: Courier;">partition</span> is that it works in linear time; assuming a list of N items, then each use of <span style="font-family: Courier;">partition</span> will apply the condition check N times and swap items in the list at most N/2 times. [1]</p>
<p>Here&#8217;s what <span style="font-family: Courier;">partition</span> looks like in Python (translated from SGI&#8217;s version of the STL algorithm [2]; comments added by me based on the SGI docs.)</p>

<div class="wp_syntax"><div class="code"><pre class="python"><span style="color: #ff7700;font-weight:bold;">def</span> partition<span style="color: black;">&#40;</span>pred, seq, first, last<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot; Partition reorders the elements in seq in the range [first, last)
        based on the function pred, such that the elements
        that satisfy pred precede the elements that fail to satisfy it.
        The postcondition is that, for some index value middle in the
        range [first, last), pred(x) is true for every item x in the
        range [first, middle) and false for every item x in the range
        [middle, last). The return value of partition is middle. &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># quick error check on the list indices</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> first &gt; last:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #ff4500;">0</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># find first element that fails to satisfy the predicate</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span>first, last<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> pred<span style="color: black;">&#40;</span>seq<span style="color: black;">&#91;</span>i<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">break</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> last
&nbsp;
    <span style="color: #808080; font-style: italic;"># for all remaining elements in the sequence, if we find one</span>
    <span style="color: #808080; font-style: italic;"># that satisfies the predicate, swap it with one that is known</span>
    <span style="color: #808080; font-style: italic;"># to have (possibly) failed the test. All swaps are necessary</span>
    <span style="color: #808080; font-style: italic;"># to preserve the correct ordering upon exit.</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> j <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span>i<span style="color: #ff4500;">+1</span>, last<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> pred<span style="color: black;">&#40;</span>seq<span style="color: black;">&#91;</span>j<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>:
            seq<span style="color: black;">&#91;</span>i<span style="color: black;">&#93;</span>, seq<span style="color: black;">&#91;</span>j<span style="color: black;">&#93;</span> = seq<span style="color: black;">&#91;</span>j<span style="color: black;">&#93;</span>, seq<span style="color: black;">&#91;</span>i<span style="color: black;">&#93;</span>
            i += <span style="color: #ff4500;">1</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> i</pre></div></div>

<p>We also need a predicate function to use with <span style="font-family: Courier;">partition</span>, since the <span style="font-family: Courier;">update</span> method is actually part of our <span style="font-family: Courier;">Shot</span> class and can’t be called directly. We could use a <span style="font-family: Courier;">lambda</span> function instead, but that is somewhat slower than a named function.</p>

<div class="wp_syntax"><div class="code"><pre class="python"><span style="color: #ff7700;font-weight:bold;">def</span> update_object<span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> x.<span style="color: black;">update</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Using our new <span style="font-family: Courier;">partition</span> and <span style="font-family: Courier;">update_object</span> functions, our update loop changes to:</p>

<div class="wp_syntax"><div class="code"><pre class="python">end = <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>lst<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">while</span> end:
    end = partition<span style="color: black;">&#40;</span>update_object, lst, <span style="color: #ff4500;">0</span>, end<span style="color: black;">&#41;</span></pre></div></div>

<p>This is one line longer than our list comprehension version, but we also don&#8217;t invalidate our reference to the list on each pass since <span style="font-family: Courier;">partition</span> performs in-place modification to our list. This makes it better on both counts.</p>
<p>One other item of interest is the variable <span style="font-family: Courier;">end</span>. After each pass of the loop, the <span style="font-family: Courier;">end</span> index marks the separation between &#8220;live&#8221; and &#8220;dead&#8221; objects in the list. As we noted earlier, once <span style="font-family: Courier;">end</span> reaches 0, all the items in the list can then be deleted. Look closely though &#8230; we were only deleting objects from the list before in order to filter those that didn&#8217;t need updating, but <span style="font-family: Courier;">partition</span> already does the filtering for us. Since all the objects in the list are, in fact, still good, to reuse one of them we just need to reset the object pointed to by the <span style="font-family: Courier;">end</span> index and then increment <span style="font-family: Courier;">end</span> by one. If we try to reuse one of the objects in the list and <span style="font-family: Courier;">end</span> goes beyond the last item in the list, then we can either expand the list or just ignore the request, depending on what behavior we want.</p>
<p>&nbsp;</p>
<h2>Managing details</h2>
<p>Here&#8217;s the interesting thing: by switching our code to use <span style="font-family: Courier;">partition</span>, what we&#8217;ve created is a simple <em>object pool</em>. At this point though, there are too many bookkeeping details, and it would be better to encapsulate the pool inside a class.</p>

<div class="wp_syntax"><div class="code"><pre class="python"><span style="color: #ff7700;font-weight:bold;">class</span> ObjectPool:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, **kwargs<span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>._clsname = kwargs<span style="color: black;">&#91;</span><span style="color: #483d8b;">'classname'</span><span style="color: black;">&#93;</span>
        <span style="color: #008000;">self</span>._args = kwargs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'args'</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">or</span> <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
        <span style="color: #008000;">self</span>._num_objects = <span style="color: #008000;">max</span><span style="color: black;">&#40;</span>kwargs<span style="color: black;">&#91;</span><span style="color: #483d8b;">'num'</span><span style="color: black;">&#93;</span>, <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>._pred = kwargs<span style="color: black;">&#91;</span><span style="color: #483d8b;">'update_func'</span><span style="color: black;">&#93;</span>
        <span style="color: #008000;">self</span>._max_objects = kwargs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'max'</span>, <span style="color: #008000;">self</span>._num_objects<span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;"># Create the objects</span>
        <span style="color: #008000;">self</span>._objs = <span style="color: black;">&#91;</span>apply<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._clsname, <span style="color: #008000;">self</span>._args<span style="color: black;">&#41;</span>
                      <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._num_objects<span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
        <span style="color: #008000;">self</span>._end = <span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._objs<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> _extend_list<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, args<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot; default policy is to add one object, up to max_objects ...
        override with different behavior if needed. &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #008000;">self</span>._objs.<span style="color: black;">append</span><span style="color: black;">&#40;</span>apply<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._clsname, args<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>._num_objects += <span style="color: #ff4500;">1</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> add<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, *args<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot; Add one new (live) object to the pool. &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        newend = <span style="color: #008000;">self</span>._end + <span style="color: #ff4500;">1</span>
        <span style="color: #808080; font-style: italic;"># if we reach our predefined maximum number of objects,</span>
        <span style="color: #808080; font-style: italic;"># don't create any more.</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> newend &gt; <span style="color: #008000;">self</span>._max_objects:
            <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">None</span>
        <span style="color: #808080; font-style: italic;"># if we bump up against the end of our list but are below the</span>
        <span style="color: #808080; font-style: italic;"># max number of objects, extend the list</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> newend &gt; <span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._objs<span style="color: black;">&#41;</span>:
            <span style="color: #008000;">self</span>._extend_list<span style="color: black;">&#40;</span>args<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">else</span>:
            <span style="color: #008000;">self</span>._objs<span style="color: black;">&#91;</span><span style="color: #008000;">self</span>._end<span style="color: black;">&#93;</span>.<span style="color: black;">reset</span><span style="color: black;">&#40;</span>*args<span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>._end += <span style="color: #ff4500;">1</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._end - <span style="color: #ff4500;">1</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> update<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, *args<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot; Update each object in the pool, using the pred function. &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #008000;">self</span>._end = partition<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._pred, <span style="color: #008000;">self</span>._objs, <span style="color: #ff4500;">0</span>, <span style="color: #008000;">self</span>._end, args<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._end</pre></div></div>

<p>That&#8217;s perhaps a lot to digest. Let&#8217;s look at a short code sample of how to use the new class that will make it easier to understand.</p>

<div class="wp_syntax"><div class="code"><pre class="python">shots = ObjectPool<span style="color: black;">&#40;</span>classname=Shot, update_func=update_object, num=<span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">while</span> shots.<span style="color: black;">update</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">pass</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Done!&quot;</span></pre></div></div>

<p>You can see here that the <span style="font-family: Courier;">ObjectPool</span> class takes keyword parameters. The first parameter, <span style="font-family: Courier;">classname</span>, specifies the name of each object’s class in the pool. The second parameter, <span style="font-family: Courier;">update_func</span>, specifies the predicate function used to update the objects. The third parameter, <span style="font-family: Courier;">num</span>, specifies the initial number of objects created. (There is also an optional fourth parameter, <span style="font-family: Courier;">max</span>, that specifies the maximum number of objects within the pool; if <span style="font-family: Courier;">max</span> isn’t explicitly specified, then it will default to <span style="font-family: Courier;">num</span>.)</p>
<p>Besides the <span style="font-family: Courier;">update</span> method we’ve already discussed, the <span style="font-family: Courier;">add</span> method will attempt to either insert a new object in the pool or reset an existing object whose <span style="font-family: Courier;">lifetime</span> has expired. (The <span style="font-family: Courier;">add</span> method assumes that each object in the pool has implemented a <span style="font-family: Courier;">reset</span> method that reinitializes the object.) If neither option is possible (the pool has reached its <span style="font-family: Courier;">max</span> or no objects have expired), then <span style="font-family: Courier;">add</span> will simply return <span style="font-family: Courier;">None</span> to indicate a failure. (You can override the <span style="font-family: Courier;">_extend_list</span> method if you wish to change this default behavior.)</p>
<p>&nbsp;</p>
<h2>A short demo of object pooling</h2>
<p>To demonstrate the utility of this code, I’ve modified Alex Holkner’s Noisy demo in the <a href="http://www.pyglet.org">pyglet 1.1.2 distribution</a> to use my <span style="font-family: Courier;">ObjectPool</span> class. His example program displays balls bouncing around the edges of a windowed display. Normally the balls bounce indefinitely until the user presses a Delete key, but I changed the demo to have the balls exist for only a short time before they are deleted from the display. The sample also demonstrates how the <span style="font-family: Courier;">ObjectPool</span> prevents you from adding more than the max number of objects defined in its constructor. This demo, along with the provided unit tests, should give you a good starting point for using <span style="font-family: Courier;">ObjectPool</span> in your own games or applications.</p>
<p>&nbsp;</p>
<p><a href="http://mysite.verizon.net/bcorfman/op.zip">Download op.zip (17 Kb)</a></p>
<p>&nbsp;</p>
<p>References:<br />
[1] <a href="http://www.sgi.com/tech/stl/partition.html">http://www.sgi.com/tech/stl/partition.html</a><br />
[2] <a href="http://www.sgi.com/tech/stl/stl_algo.h">http://www.sgi.com/tech/stl/stl_algo.h</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/object-pooling-in-python/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A New Author for the Blog and Site</title>
		<link>http://www.devpicayune.com/entry/a-new-author-for-the-blog-and-site</link>
		<comments>http://www.devpicayune.com/entry/a-new-author-for-the-blog-and-site#comments</comments>
		<pubDate>Thu, 20 Nov 2008 16:57:38 +0000</pubDate>
		<dc:creator>ScW</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/?p=142</guid>
		<description><![CDATA[I&#8217;ve never really regretted keeping two separate blogs. Three was certainly too much, but having two isn&#8217;t all bad. The one thing I&#8217;ve regretted is that I&#8217;ve not done enough posts. So, to help fix that situation and also to provide a slightly more permanent home to the excellent posts that he writes, I&#8217;m pleased [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve never really regretted keeping two separate blogs. Three was certainly too much, but having two isn&#8217;t all bad. The one thing I&#8217;ve regretted is that I&#8217;ve not done enough posts. So, to help fix that situation and also to provide a slightly more permanent home to the excellent posts that he writes, I&#8217;m pleased to announce that Brandon Corfman is now going to be co-author, if not primary author, here on this site. Brandon brings both a more academically grounded education background together with even broader practical experience programming.</p>
<p>Brandon is single-handed responsible for my initial interest in Python as well being the greatest of friends. So now it&#8217;s official, this site, now has gained a whole lot more credibility. At the same time, perhaps Brandon&#8217;s input will spur me on to write a few more things here as well. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/a-new-author-for-the-blog-and-site/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Some Long MySQL Connection Delays</title>
		<link>http://www.devpicayune.com/entry/some-long-mysql-connection-delays</link>
		<comments>http://www.devpicayune.com/entry/some-long-mysql-connection-delays#comments</comments>
		<pubDate>Tue, 30 Sep 2008 13:39:33 +0000</pubDate>
		<dc:creator>ScW</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[vmware]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/?p=120</guid>
		<description><![CDATA[This issue has been documented before, but it took me awhile to understand what the real problem was and what my options for resolving it were.
So what happened? I had a VM (Ubuntu Hardy) chillin&#8217; on my local dev box. That local VM was a test environment to verify the performance of a django app [...]]]></description>
			<content:encoded><![CDATA[<p>This issue has been documented before, but it took me awhile to understand what the real problem was and what my options for resolving it were.</p>
<p>So what happened? I had a VM (Ubuntu Hardy) chillin&#8217; on my local dev box. That local VM was a test environment to verify the performance of a django app being hosted on a VM with Apache and mod_wsgi. And wouldn&#8217;t you know it? It was slow&#8230; very slow. As in 5 seconds per browse to display or anytime it had to hit the database. Dropping to the command-line revealed that it was the actual connecting to the mysql server (which is a separate server) that was taking most of all that time.</p>
<p>As it turns out, MySQL&#8217;s name lookup (reverse address resolution) was causing the slowdown. You can turn off MySQL&#8217;s reverse lookup using the &#8220;&#8211;skip-name-resolve&#8221; option. But since changing the configuration of a running MySQL server (production) is not an option, I had to figure out something else. The VM was getting a DHCP address and since our in-house (Windows-based) DNS doesn&#8217;t do well at tracking the names of DHCP&#8217;d clients that are Linux boxes, our DNS stinks at getting the name in any timely fashion. But, if you assign the client a static IP that has an official name in our DNS, voila! You have a nice, fast connection time again. A Windows box in my office, that gets assigned an IP via DHCP is fine as well, presumably because our DNS server plays well with other Windows boxes.</p>
<p>As I stated earlier, you can disable the name lookup but then you have to use IP addresses if you want to support security based on the connecting client&#8217;s machine. Making sure there are DNS entries for the clients seems to fix it. Again, this is mostly just for my own record if nothing else. I certainly don&#8217;t want to see this crop up again and not remember what I figured out.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/some-long-mysql-connection-delays/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hosting a Django Site With the CherryPy WSGI Server</title>
		<link>http://www.devpicayune.com/entry/hosting-django-with-cherrypy-wsgi-server</link>
		<comments>http://www.devpicayune.com/entry/hosting-django-with-cherrypy-wsgi-server#comments</comments>
		<pubDate>Tue, 22 Apr 2008 19:43:53 +0000</pubDate>
		<dc:creator>ScW</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/?p=119</guid>
		<description><![CDATA[So after hearing about CherryPy&#8217;s WSGI server while at PyCon (I went to the Pylons/TG2 classes), I decided, like others have, to see if I could host a Django site with it here where I work.  There are several references out there about using that server code with Django, but I had a tough [...]]]></description>
			<content:encoded><![CDATA[<p>So after hearing about CherryPy&#8217;s WSGI server while at PyCon (I went to the Pylons/TG2 classes), I decided, like others have, to see if I could host a Django site with it here where I work.  There are several references out there about using that server code with Django, but I had a tough time getting to the point where I could actually use it to handle the Admin media.  Some of the articles were slightly out of date with changes made to the most recent version of the CherryPy WSGI server, so while this is drawing off of several other folk&#8217;s work (like <a href="http://www.eflorenzano.com/blog/post/hosting-django-site-pure-python/">Eric Florenzano</a> and <a href="http://www.xhtml.net/scripts/Django-CherryPy-server-DjangoCerise">DjangoCerise</a> ), I present what I did to make it work while also realizing that this is probably still very incomplete.  I am just hoping this will help someone get started.</p>
<p>Prior to the code, I downloaded just the wsgiserver.py from CherryPy.  You can get the latest from trunk if you&#8217;re running Linux, with just a command like this:</p>
<pre>
wget http://svn.cherrypy.org/trunk/cherrypy/wsgiserver/__init__.py -O wsgiserver.py
</pre>
<p>Then I also wanted to have some logging capabilities, so I discovered <a href="http://pythonpaste.org/module-paste.translogger.html">Paste&#8217;s TransLogger middleware</a>.  All you have to do is download the translogger.py file from the paste project (sorry no quicky command for that, I grabbed it via the browser and I am too lazy to get you the command for that).</p>
<p>So with those 2 files (wsgiserver.py and translogger.py) now in the main directory of my particular django project (dash2 is the name in my example), I created a new cherryserve.py in that same directory as well.</p>

<div class="wp_syntax"><div class="code"><pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> wsgiserver
<span style="color: #808080; font-style: italic;">#This can be from cherrypy import wsgiserver if you're not running it standalone.</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
<span style="color: #ff7700;font-weight:bold;">import</span> django.<span style="color: black;">core</span>.<span style="color: black;">handlers</span>.<span style="color: black;">wsgi</span>
<span style="color: #ff7700;font-weight:bold;">from</span> django.<span style="color: black;">core</span>.<span style="color: black;">servers</span>.<span style="color: black;">basehttp</span> <span style="color: #ff7700;font-weight:bold;">import</span> AdminMediaHandler
<span style="color: #ff7700;font-weight:bold;">from</span> translogger <span style="color: #ff7700;font-weight:bold;">import</span> TransLogger
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    <span style="color: #dc143c;">sys</span>.<span style="color: black;">path</span>.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'/home/swilcox/projects'</span><span style="color: black;">&#41;</span>
    <span style="color: #dc143c;">os</span>.<span style="color: black;">environ</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'DJANGO_SETTINGS_MODULE'</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">'dash2.settings'</span>
&nbsp;
    app = AdminMediaHandler<span style="color: black;">&#40;</span>django.<span style="color: black;">core</span>.<span style="color: black;">handlers</span>.<span style="color: black;">wsgi</span>.<span style="color: black;">WSGIHandler</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    logged_app = TransLogger<span style="color: black;">&#40;</span>app<span style="color: black;">&#41;</span>
    server = wsgiserver.<span style="color: black;">CherryPyWSGIServer</span><span style="color: black;">&#40;</span>	
        <span style="color: black;">&#40;</span><span style="color: #483d8b;">'127.0.0.1'</span>, <span style="color: #ff4500;">8080</span><span style="color: black;">&#41;</span>,
        logged_app,
        server_name=<span style="color: #483d8b;">'luz.lifeway.org'</span>,
        numthreads = <span style="color: #ff4500;">20</span>,
    <span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        server.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">KeyboardInterrupt</span>:
        server.<span style="color: black;">stop</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>So why did I do the path trickery up there?  Well, because in my development environment, I don&#8217;t want my entire projects directory normally on my python path.  Feel free to call me paranoid.  But to get the server to work correctly with the django code, I needed it there.  For a production server, the <code>sys.path.append </code> business wouldn&#8217;t normally need to be there, because I would have my apps or projects directory as part of the Python path.  </p>
<p>Also note that if you needed to serve multiple apps, with this newer version of the wsgiserver.py, you would want to set them all up in a <code>WSGIPathInfoDispatcher</code> object first and then pass that in to the <code>CherryPyWSGIServer</code> instead of <code>logged_app</code>.</p>
<p>I think the other fields are pretty self-explanatory&#8230; ports, IP address, threads, etc&#8230; </p>
<p>The Admin Media trick is using <code>app = AdminMediaHandler(django.core.handlers.wsgi.WSGIHandler())</code> instead of just the <code>WSGIHandler</code> by itself. </p>
<p>If you don&#8217;t want the logger, you just pass in <code>app</code> instead of <code>logged_app</code>.  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/hosting-django-with-cherrypy-wsgi-server/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MySQLdb and executemany error &#8220;incomplete format&#8221;</title>
		<link>http://www.devpicayune.com/entry/mysqldb-and-executemany-error-incomplete-format</link>
		<comments>http://www.devpicayune.com/entry/mysqldb-and-executemany-error-incomplete-format#comments</comments>
		<pubDate>Thu, 17 Jan 2008 22:11:22 +0000</pubDate>
		<dc:creator>ScW</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/entry/mysqldb-and-executemany-error-incomplete-format</guid>
		<description><![CDATA[Okay, very weird problem today.  I am not sure what to make of it&#8230; when using the latest version of MySQLdb (1.2.2.final.0) which is the version in Ubuntu 7.10 Gutsy, I am getting an &#8220;incomplete format&#8221; error when performing an executemany.  My variables are presented as a list of dictionaries as I&#8217;m using [...]]]></description>
			<content:encoded><![CDATA[<p>Okay, very weird problem today.  I am not sure what to make of it&#8230; when using the latest version of MySQLdb (1.2.2.final.0) which is the version in Ubuntu 7.10 Gutsy, I am getting an &#8220;incomplete format&#8221; error when performing an executemany.  My variables are presented as a list of dictionaries as I&#8217;m using named/mapped variables in the SQL statement.  Using the exact same code with MySQLdb (1.2.1.final.2) is fine (the version in Ubuntu Feisty 7.04).</p>
<p>So for completeness sake, I have documented the scenario like this:</p>
<p>On a MySQL server, you just need a simple little table:</p>

<div class="wp_syntax"><div class="code"><pre class="sql"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #ff0000;">`test_table`</span> <span style="color: #66cc66;">&#40;</span>
<span style="color: #ff0000;">`id`</span> int<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">UNSIGNED</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #993333; font-weight: bold;">AUTO_INCREMENT</span>,
<span style="color: #ff0000;">`test_col_1`</span> varchar<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">20</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span>,
<span style="color: #ff0000;">`test_col_2`</span> varchar<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">20</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span>,
<span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span>  <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">`id`</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span> ENGINE=MyISAM <span style="color: #993333; font-weight: bold;">AUTO_INCREMENT</span>=<span style="color: #cc66cc;">2</span> <span style="color: #993333; font-weight: bold;">DEFAULT</span> CHARSET=latin1</pre></div></div>

<p>Then the Python code (obviously you&#8217;ll need to set the connection stuff appropriately):</p>

<div class="wp_syntax"><div class="code"><pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> MySQLdb
&nbsp;
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;-----------------------------------------------------&quot;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> MySQLdb.<span style="color: black;">version_info</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;-----------------------------------------------------&quot;</span>
&nbsp;
sqlStringItems = <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;INSERT INTO test_table
(test_col_1,test_col_2)
VALUES
(%(test1)s, %(test2)s);&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
dtlDict = <span style="color: black;">&#123;</span><span style="color: #483d8b;">'test1'</span>:<span style="color: #483d8b;">'test value 1'</span>,<span style="color: #483d8b;">'test2'</span>:<span style="color: #483d8b;">'test value 2'</span><span style="color: black;">&#125;</span>
&nbsp;
con = MySQLdb.<span style="color: black;">connect</span><span style="color: black;">&#40;</span>host=<span style="color: #483d8b;">&quot;localhost&quot;</span>,<span style="color: #dc143c;">user</span>=<span style="color: #483d8b;">&quot;myuser&quot;</span>,passwd=<span style="color: #483d8b;">&quot;mypassword&quot;</span>,db=<span style="color: #483d8b;">&quot;test&quot;</span><span style="color: black;">&#41;</span>
cur = con.<span style="color: black;">cursor</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
exitval = cur.<span style="color: black;">executemany</span><span style="color: black;">&#40;</span>sqlStringItems,<span style="color: black;">&#91;</span>dtlDict<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;exit value from executemany= &quot;</span> + <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>exitval<span style="color: black;">&#41;</span>
cur.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>version (1, 2, 2, &#8216;final&#8217;, 0) yields:</p>
<pre>ValueError: incomplete format</pre>
<p>Whereas version (1, 2, 1, &#8216;final&#8217;, 2) works fine.</p>
<p>Also, doing the same thing, but with <code>execute</code> instead of <code>executemany</code> works fine (and of course taking the dict out of the list).  So this seems to be purely an issue with executemany.  Looking at the MySQLdb code, it&#8217;s obvious that between the two versions it was pretty radically changed.</p>
<p>I guess I need to report this as a bug, but I&#8217;m just finding it hard to believe that I didn&#8217;t do something wrong.</p>
<p><strong>Update (2008-06-03)</strong><br />
Back in January, I reported <a href="http://sourceforge.net/tracker/index.php?func=detail&#038;aid=1874176&#038;group_id=22307&#038;atid=374932">this issue (1874176)</a>. Then in late April, Raphael Guillet submitted a possible fix. I haven&#8217;t spent much time looking at the right vs. wrong of the fix, but I have tried it and it appears to work. So for those looking, here&#8217;s the possible fix which as near as I can tell has still not been cut into the official version.</p>
<p>The change is in the cursors.py file. So you have to hunt that down wherever it is stored in your particular OS version and/or install.</p>
<p>Comment out lines 201 and 202:</p>

<div class="wp_syntax"><div class="code"><pre class="python">        <span style="color: #808080; font-style: italic;">#e = m.end(1)</span>
        <span style="color: #808080; font-style: italic;">#qv = m.group(1)</span></pre></div></div>

<p>And then add right after that:</p>

<div class="wp_syntax"><div class="code"><pre class="python">        e=<span style="color: #008000;">len</span><span style="color: black;">&#40;</span>query<span style="color: black;">&#41;</span>
        qv = query<span style="color: black;">&#91;</span>p:e<span style="color: black;">&#93;</span></pre></div></div>

<p>I&#8217;ll try to continue to monitor this.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/mysqldb-and-executemany-error-incomplete-format/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Projects, PyCon, and Life</title>
		<link>http://www.devpicayune.com/entry/projects-pycon-and-life</link>
		<comments>http://www.devpicayune.com/entry/projects-pycon-and-life#comments</comments>
		<pubDate>Sun, 25 Nov 2007 07:33:51 +0000</pubDate>
		<dc:creator>ScW</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[pycon]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/entry/projects-pycon-and-life</guid>
		<description><![CDATA[So just as a bookmark to myself, I wanted to document what all I was working on from a technical perspective.
On the work front, I&#8217;ve recently deployed a Django app that folks are just totally loving.  It&#8217;s actually a hacked together group of scripts to import data and export data to two different legacy [...]]]></description>
			<content:encoded><![CDATA[<p>So just as a bookmark to myself, I wanted to document what all I was working on from a technical perspective.</p>
<p>On the work front, I&#8217;ve recently deployed a Django app that folks are just totally loving.  It&#8217;s actually a hacked together group of scripts to import data and export data to two different legacy systems.  In the middle, I use the Django admin stuff to allow folks to maintain the data, and scripts at the beginning and end of the day handle import and export duties.</p>
<p>I finally started hacking around on WordPress themes.  I&#8217;ve not gotten very far but hopefully in the next week or so, I&#8217;ll have new designs for both sites.</p>
<p>Then, with regard to PyCon, I submitted some talk proposals.  Not sure I should have bothered, but it seemed like the thing to do.  Now I&#8217;m just curious to see if any of my proposals are accepted.  One of the proposals is for a project I&#8217;ve only begun really gathering the pieces for.  I&#8217;ve resolved that whether the talk is approved or not, I&#8217;m going to work away at the project and then I&#8217;ll either have a talk or I&#8217;ll have a lightning talk to present.  I&#8217;ll be blogging my way through my progress here, so should have some interesting stuff to post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/projects-pycon-and-life/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More Blog Housekeeping</title>
		<link>http://www.devpicayune.com/entry/more-blog-housekeeping</link>
		<comments>http://www.devpicayune.com/entry/more-blog-housekeeping#comments</comments>
		<pubDate>Sat, 10 Nov 2007 18:25:54 +0000</pubDate>
		<dc:creator>ScW</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pumkinvine]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[spam]]></category>
		<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/entry/more-blog-housekeeping</guid>
		<description><![CDATA[I&#8217;ve finally gotten tired of my poor little blog getting attacked by spammers.  Actually, it was just one in particular and I know I could&#8217;ve done some IP blocking or added to the protection scheme on my comments, but rather than working more on Pumpkinvine, I&#8217;ve now switched to WordPress.  And while it [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve finally gotten tired of my poor little blog getting attacked by spammers.  Actually, it was just one in particular and I know I could&#8217;ve done some IP blocking or added to the protection scheme on my comments, but rather than working more on Pumpkinvine, I&#8217;ve now switched to WordPress.  And while it seems like I&#8217;m giving up, it&#8217;s really so I have the chance to catch my breath while I use all the WordPress plugins to handle the spam for me.  But for reference, I ought to package up my most recent version of Pumpkinvine and make it available for folks although it&#8217;s really a pretty rough collection of PHP scripts that approximate the same style as <a href="http://www.blosxom.com/">blosxom</a>.  So why bother creating another system?  But it seemed like a good idea at the time.  Probably the neatest part of Pumpkinvine was going to be the switchable back-ends so you could choose between text files, SQLite, MySQL or something else by just changing a single setting.  Of course, the only back-end I had done was the text files-based core.</p>
<p>Ultimately, I was tired of messing with PHP.  I&#8217;d like to go with more Python.  Django appears to the fastest way to get to having a working blog, but lack of personal free time, and lack of desire to fight with FastCGI and Dreamhost to get up and running, kind of dampened my spirits.  So I&#8217;ll settle for my clever Python script that I wrote to convert from Pumpkinvine to WordPress and some time that I&#8217;ll need to devote to learning how to create WordPress themes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/more-blog-housekeeping/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
