<?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 &#187; python</title>
	<atom:link href="http://www.devpicayune.com/entry/category/python/feed" rel="self" type="application/rss+xml" />
	<link>http://www.devpicayune.com</link>
	<description>picayune: of little value or importance</description>
	<lastBuildDate>Mon, 18 Apr 2011 21:56:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Raven Checkers 0.4 released</title>
		<link>http://www.devpicayune.com/entry/raven-checkers-0-4-released</link>
		<comments>http://www.devpicayune.com/entry/raven-checkers-0-4-released#comments</comments>
		<pubDate>Mon, 18 Apr 2011 19:09:32 +0000</pubDate>
		<dc:creator>Brandon Corfman</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.devpicayune.com/?p=216</guid>
		<description><![CDATA[I recently released a new 0.4 version of Raven Checkers. Windows download here. Raven is a checkers game program, for one or two players. While there are examples of excellent &#38; free checkers programs out on the net (such as Martin Fierz&#8217;s Checkerboard), Raven has a few differences. Open-source code. Raven uses existing open source code [...]]]></description>
			<content:encoded><![CDATA[<p>I recently released a new 0.4 version of Raven Checkers. <a href="http://code.google.com/p/raven-checkers/downloads/list">Windows download here</a>.</p>
<p><img class=" alignnone" title="Raven 0.4" src="http://mysite.verizon.net/bcorfman/uploaded_images/raven.png" alt="Raven Checkers 0.4 GUI" width="487" height="297" /></p>
<p>Raven is a checkers game program, for one or two players. While there are examples of excellent &amp; free checkers programs out on the net (such as <a rel="nofollow" href="http://www.fierz.ch/checkers.htm">Martin Fierz&#8217;s Checkerboard</a>), Raven has a few differences.</p>
<ul>
<li><strong>Open-source code</strong>. Raven uses existing open source code as a basis (<a rel="nofollow" href="http://www.fierz.ch/engines.php">Martin Fierz&#8217;s Simple Checkers evaluation function</a> and <a rel="nofollow" href="http://aima.cs.berkeley.edu/python/readme.html">Peter Norvig&#8217;s search code from the AIMA project</a>) for its AI engine.</li>
</ul>
<ul>
<li><strong>Cross-platform</strong>. Raven is written using Python 2.7 using its standard libraries and works on both Windows and Linux with its Tkinter GUI.</li>
</ul>
<ul>
<li><strong>Great for checkers study</strong>. Raven allows you to quickly set up board configurations using standard checkerboard notation. You can also describe your moves in the annotation window, and you can save and load games for later study. This is great for working through checkers books and learning techniques and tactics. I&#8217;ve included several training files in this version to show how well Raven works for studying endgame strategy.</li>
</ul>
<p><strong>I&#8217;m looking for volunteers to help with Raven! </strong>Take a look at future plans below and see if you&#8217;d be willing to join the project:</p>
<p>Most checkers or chess programs go the route of deep search combined with perfect opening and endgame databases. These techniques are well-explored and not really all that interesting to me. I plan on making a big change in future versions of Raven by relying more on planning than brute-force search.</p>
<p>Here&#8217;s what I&#8217;m thinking:</p>
<ul>
<li>Implement a behavior tree AI (perhaps using <a rel="nofollow" href="http://code.google.com/p/owyl/">Owyl</a>) that will devise opening themes and endgame strategies. These plans will be based on tactics and endings from Richard Pask&#8217;s books <a rel="nofollow" href="http://www.jimloy.com/checkers/pask.htm">Starting Out in Checkers</a> and <a rel="nofollow" href="http://www.bobnewell.net/checkers/bookorders/getpbcd1.html">Play Better Checkers &amp; Draughts</a>, which I use in my own checkers study.</li>
<li>Add a transposition table and some move ordering to help with alpha-beta search depth. (I will probably make use of the transposition table code in <a rel="nofollow" href="http://pychess.googlepages.com/">PyChess</a> or <a rel="nofollow" href="http://pypi.python.org/pypi/chesstools/0.1.2">Chesstools</a>.) Despite my preference for using a behavior tree for high-level plans, I would like to be able to fall back on good search for the early- and late-midgame when play becomes a bit more muddled.</li>
<li>Release a Linux distribution. (I&#8217;d love to use PyInstaller or cx_freeze for this, but I have little experience. I could definitely use some help with this &#8230; my appeals for help to the StackOverflow community have gone largely unnoticed.)</li>
<li>Switch the search/game tree algorithms to use generators instead of lists to improve speed &amp; memory usage.</li>
<li>Make the undo and redo work completely correct with the background AI processing.</li>
<li>Improve the annotation feature (currently using a simple Creole text format) to be more WYSIWYG.</li>
</ul>
<p>If you&#8217;re interested, <a href="http://code.google.com/p/raven-checkers/source/browse/">browse</a> the code or <a href="http://code.google.com/p/raven-checkers/source/checkout">clone it</a>, see what appeals to you in the list above, and let me know you want to jump in by <a href="http://groups.google.com/group/raven-checkers?pli=1">posting on the newsgroup</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/raven-checkers-0-4-released/feed</wfw:commentRss>
		<slash:comments>2</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>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; [...]]]></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" style="font-family:monospace;"><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> <span style="color: #66cc66;">&gt;</span> <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" style="font-family:monospace;"><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" style="font-family:monospace;"><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;&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;&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 <span style="color: #66cc66;">&gt;</span> 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" style="font-family:monospace;"><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" style="font-family:monospace;">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" style="font-family:monospace;"><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>, <span style="color: #66cc66;">**</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;&quot; default policy is to add one object, up to max_objects ...
        override with different behavior if needed. &quot;&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>, <span style="color: #66cc66;">*</span>args<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;&quot; Add one new (live) object to the pool. &quot;&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 <span style="color: #66cc66;">&gt;</span> <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 <span style="color: #66cc66;">&gt;</span> <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><span style="color: #66cc66;">*</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>, <span style="color: #66cc66;">*</span>args<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;&quot; Update each object in the pool, using the pred function. &quot;&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" style="font-family:monospace;">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>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 named/mapped variables [...]]]></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" style="font-family:monospace;"><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> <span style="color: #993333; font-weight: bold;">INT</span><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: #66cc66;">,</span>
<span style="color: #ff0000;">`test_col_1`</span> <span style="color: #993333; font-weight: bold;">VARCHAR</span><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: #66cc66;">,</span>
<span style="color: #ff0000;">`test_col_2`</span> <span style="color: #993333; font-weight: bold;">VARCHAR</span><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: #66cc66;">,</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<span style="color: #66cc66;">=</span>MyISAM <span style="color: #993333; font-weight: bold;">AUTO_INCREMENT</span><span style="color: #66cc66;">=</span><span style="color: #cc66cc;">2</span> <span style="color: #993333; font-weight: bold;">DEFAULT</span> CHARSET<span style="color: #66cc66;">=</span>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" style="font-family:monospace;"><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;&quot;INSERT INTO test_table
(test_col_1,test_col_2)
VALUES
(%(test1)s, %(test2)s);&quot;&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" style="font-family:monospace;">        <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" style="font-family:monospace;">        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>10</slash:comments>
		</item>
		<item>
		<title>An Odd Monday Calendar Bit of Nonsense</title>
		<link>http://www.devpicayune.com/entry/200708271353</link>
		<comments>http://www.devpicayune.com/entry/200708271353#comments</comments>
		<pubDate>Mon, 27 Aug 2007 19:53:06 +0000</pubDate>
		<dc:creator>ScW</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[(now updated with some pointless Python code) This is perfect for this little blog concerned with trivial and small things. I noticed that my Peanuts calendar on my desk is essentially a reproduction of the 1990 calendar. Obviously, they all have to be reproductions because Charles Schulz died in 2000. So looking more closely, I [...]]]></description>
			<content:encoded><![CDATA[<p> <em>(now updated with some pointless Python code)</em></p>
<p>This is perfect for this little blog concerned with trivial and small things.  I noticed that my Peanuts calendar on my desk is essentially a reproduction of the 1990 calendar.  Obviously, they all have to be reproductions because Charles Schulz died in 2000.  So looking more closely, I realized they&#8217;d chosen 1990 primarily because the dates and days of 1990 match 2007.  So a quick hack with the &#8216;cal&#8217; program under linux and I was off and searching for what will most likely be next year&#8217;s calendar.  Since 2008 is a leap year and obviously 1991 is not, I knew that wasn&#8217;t going to work.</p>
<p>First I generated target calendar with:</p>
<pre>cal 2008 &gt; cal2008.txt</pre>
<p>Then, I just manually (although I could have written a script) looped through a few known leap years and found that 1980 seems to match perfectly as well.</p>
<pre>cal 1980|diff - cal2008.txt</pre>
<p>Obviously, what we&#8217;re looking for is a diff of only the first line, the year.  Side note: the selection of 1952 (also a match), would seem to be fairly unlikely.</p>
<p>For 2009, there are a bunch of choices including: 1953, 1959, 1970, 1981, 1987 and 1998.</p>
<p>Why am I posted this?  I don&#8217;t know other than it was fun to use &#8216;cal&#8217; and &#8216;diff&#8217; to anticipate which Peanuts calendar would be next.</p>
<p><strong>UPDATE</strong></p>
<p>I couldn&#8217;t resist doing a Python solution to this little problem.  I know this isn&#8217;t as efficient as someone else could make it, but it was entertaining for me to do it.  It took about 5 or 6 minutes to write and ran correctly the first time (matching my previous results):</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><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;">datetime</span>
<span style="color: #ff7700;font-weight:bold;">def</span> matchCals<span style="color: black;">&#40;</span>inputYear,minYear,maxYear<span style="color: black;">&#41;</span>:
    sDayOfWeek = <span style="color: #dc143c;">datetime</span>.<span style="color: black;">date</span><span style="color: black;">&#40;</span>inputYear,<span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>.<span style="color: black;">weekday</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    eDayOfWeek = <span style="color: #dc143c;">datetime</span>.<span style="color: black;">date</span><span style="color: black;">&#40;</span>inputYear,<span style="color: #ff4500;">12</span>,<span style="color: #ff4500;">31</span><span style="color: black;">&#41;</span>.<span style="color: black;">weekday</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> testYear <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span>minYear,maxYear+<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: black;">&#40;</span>sDayOfWeek == <span style="color: #dc143c;">datetime</span>.<span style="color: black;">date</span><span style="color: black;">&#40;</span>testYear,<span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>.<span style="color: black;">weekday</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">and</span> eDayOfWeek == <span style="color: #dc143c;">datetime</span>.<span style="color: black;">date</span><span style="color: black;">&#40;</span>testYear,<span style="color: #ff4500;">12</span>,<span style="color: #ff4500;">31</span><span style="color: black;">&#41;</span>.<span style="color: black;">weekday</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Match Found... %s = %s&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">str</span><span style="color: black;">&#40;</span>testYear<span style="color: black;">&#41;</span> , <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>inputYear<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    matchCals<span style="color: black;">&#40;</span><span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>, <span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>, <span style="color: #008000;">int</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">3</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Here I just check the day of the week on the first day of the year, and the last day of the year.  If both of those fall on the same day, I assume the calendars for those years are the same.  And since we&#8217;re dealing with a limited set of dates (valid complete Peanuts calendars running roughly 1951 to 1999, it handles a min and max year for input as well.  So to run it for 2008, you just type in:</p>
<pre>python ./caltest.py 2008 1951 1999</pre>
<p>Of course, there is no error checking&#8230; so if you enter a string or an invalid year&#8230; that&#8217;s your own problem.  I just wanted to see how quick I could do it.  Obviously, I&#8217;ve waisted more of my time&#8230; and more of your time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devpicayune.com/entry/200708271353/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

