<?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>I See Dead Code &#187; python</title>
	<atom:link href="http://shlomme.diotavelli.net/category/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://shlomme.diotavelli.net</link>
	<description>… as sounding brass, or a tinkling cymbal.</description>
	<lastBuildDate>Sun, 12 Jul 2009 19:38:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Breaking Event Cycles</title>
		<link>http://shlomme.diotavelli.net/2009/07/12/breaking-event-cycles/</link>
		<comments>http://shlomme.diotavelli.net/2009/07/12/breaking-event-cycles/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 19:38:04 +0000</pubDate>
		<dc:creator>shlomme</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://shlomme.diotavelli.net/?p=242</guid>
		<description><![CDATA[A recurring problem in (not only) GUI programming are event cycles, i.e. the receiving of events oneself has triggered. These can quickly lead to event cycles, where change triggers change triggers change, until something gives out—usually the stack.
A particularly cheap way of breaking cycles are simple boolean flags:

class Foo&#40;object&#41;:
   listen = True
  [...]]]></description>
			<content:encoded><![CDATA[<p>A recurring problem in (not only) GUI programming are event cycles, i.e. the receiving of events oneself has triggered. These can quickly lead to event cycles, where change triggers change triggers change, until something gives out—usually the stack.</p>
<p>A particularly cheap way of breaking cycles are simple boolean flags:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> Foo<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
   listen = <span style="color: #008000;">True</span>
   <span style="color: #ff7700;font-weight:bold;">def</span> some_method<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;">listen</span> = <span style="color: #008000;">False</span>
       <span style="color: #ff7700;font-weight:bold;">try</span>:
           <span style="color: #808080; font-style: italic;"># do stuff that triggers some_event</span>
       <span style="color: #ff7700;font-weight:bold;">finally</span>: 
            <span style="color: #008000;">self</span>.<span style="color: black;">listen</span> = <span style="color: #008000;">True</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> on_some_event<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: #008000;">self</span>.<span style="color: black;">listen</span>:
            <span style="color: #ff7700;font-weight:bold;">return</span>
        <span style="color: #808080; font-style: italic;"># handle event normally</span></pre></div></div>

<p>Boolean flags are great. They&#8217;re simple, they&#8217;ll make your code harder and half of the time, you&#8217;ll forget to set them to <tt>True</tt> after you&#8217;re done. Or you forget the <tt>try...finally...</tt> block. Or you forget to check them in the event handler. What could possibly go wrong.<br />
<!-- more --></p>
<p>Fortunately, some GUI toolkits provide ways to temporarily disable event handling for specific events, like GObject&#8217;s <a href="http://library.gnome.org/devel/pygobject/stable/class-gobject.html#method-gobject--handler-block-by-func"><tt>handler_block_by_func</tt></a>. This approach has two problems:</p>
<ul>
<li>You have to know the object (or objects) that emits the event.</li>
<li>It only works for GObject events (signals).</li>
</ul>
<p>Since I do have classes with their own event handling mechanism, in order to be independent of GObject and since it&#8217;s not really difficult to implement, I wanted a cross-event-framework way of temporarily blocking event handling. Or, maybe I just wanted to write another decorator/context manager very badly. Maybe a little bit of both.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> Foo<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> some_method<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">with</span> <span style="color: #008000;">self</span>.<span style="color: black;">on_some_event</span>.<span style="color: black;">suspend</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
            <span style="color: #808080; font-style: italic;"># do stuff that triggers some_event</span>
&nbsp;
    @suspendable
    <span style="color: #ff7700;font-weight:bold;">def</span> on_some_event<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #808080; font-style: italic;"># handle event normally</span></pre></div></div>

<p>The event handlers are wrapped inside another method which swallows the event when the context manager is in suspended mode. The code remains blissfully ignorant of threading issues for now and also breaks down if the event handlers have meaningful result values. I&#8217;ve never encountered this so far, but adding default return values to the decorator is a simple extension. The methods are still proper bound methods and docstrings etc. are all conserved. </p>
<p>Without further ado, the code:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> Suspender<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><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">is_suspended</span> = <span style="color: #ff4500;">0</span>
&nbsp;
    @contextmanager
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__call__</span><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;">is_suspended</span> += <span style="color: #ff4500;">1</span>
        <span style="color: #ff7700;font-weight:bold;">try</span>:
            <span style="color: #ff7700;font-weight:bold;">yield</span>
        <span style="color: #ff7700;font-weight:bold;">finally</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">is_suspended</span> -= <span style="color: #ff4500;">1</span>
&nbsp;
    @<span style="color: #008000;">classmethod</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> suspendable<span style="color: black;">&#40;</span>cls, meth<span style="color: black;">&#41;</span>:
        suspend_manager = cls<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
        wrapper = suspend_manager.<span style="color: black;">add_suspendable</span><span style="color: black;">&#40;</span>meth<span style="color: black;">&#41;</span>
        wrapper.<span style="color: black;">suspend</span> = suspend_manager
        wrapper.<span style="color: black;">add_suspendable</span> = suspend_manager.<span style="color: black;">add_suspendable</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> wrapper
&nbsp;
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> add_suspendable<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, meth<span style="color: black;">&#41;</span>:
        @wraps<span style="color: black;">&#40;</span>meth<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">def</span> suspended_wrapper<span style="color: black;">&#40;</span><span style="color: #66cc66;">*</span>args<span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>.<span style="color: black;">is_suspended</span> == <span style="color: #ff4500;">0</span>:
                meth<span style="color: black;">&#40;</span><span style="color: #66cc66;">*</span>args<span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #ff7700;font-weight:bold;">return</span> suspended_wrapper
&nbsp;
suspendable = Suspender.<span style="color: black;">suspendable</span></pre></div></div>

<p>It&#8217;s possible to have several event handlers block by a single context manager using the <tt>add_suspendable</tt> decorator added to suspendable methods:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">@suspendable
<span style="color: #ff7700;font-weight:bold;">def</span> on_some_event<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>: ...
&nbsp;
@on_some_event.<span style="color: black;">add_suspendable</span>
<span style="color: #ff7700;font-weight:bold;">def</span> on_misc_event<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>: ...</pre></div></div>

<p>Calling the <tt>suspend()</tt> context manager for <tt>on_some_event</tt> will also block <tt>on_misc_event</tt>.</p>
<p>The context manager does not prevent the event from being propagated, so it&#8217;s not a speed optimization; due to the added boolean check event + call indirection, handling actually becomes slightly slower. It likely won&#8217;t make a difference. If it does, event cycles are the least of your problems.</p>
]]></content:encoded>
			<wfw:commentRss>http://shlomme.diotavelli.net/2009/07/12/breaking-event-cycles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scrollable Widgets with PyGTK</title>
		<link>http://shlomme.diotavelli.net/2009/05/17/scrollable-widgets-with-pygtk/</link>
		<comments>http://shlomme.diotavelli.net/2009/05/17/scrollable-widgets-with-pygtk/#comments</comments>
		<pubDate>Sat, 16 May 2009 23:49:17 +0000</pubDate>
		<dc:creator>shlomme</dc:creator>
				<category><![CDATA[lang:en]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://shlomme.diotavelli.net/?p=178</guid>
		<description><![CDATA[It is possible to write custom GTK widgets that have &#8220;native&#8221; scrolling support, as opposed to just shoving them into a GtkViewPort and forgetting about them. 
Apart from having mastered a small coding challenge, as it turned out to be, this also gives you greater control over the scrolling itself, like making sure that certain [...]]]></description>
			<content:encoded><![CDATA[<p>It is possible to write custom GTK widgets that have &#8220;native&#8221; scrolling support, as opposed to just shoving them into a <a href="http://library.gnome.org/devel/gtk/unstable/GtkViewport.html">GtkViewPort</a> and forgetting about them. </p>
<p>Apart from having mastered a small coding challenge, as it turned out to be, this also gives you greater control over the scrolling itself, like making sure that certain elements are visible, viewport panning etc.</p>
<p>Anyway, especially when using PyGTK, it&#8217;s a bit unclear on how to proceed. From the documentation, it somehow gets clear that it has to do with the signal <code>set_scroll_adjustment_signal</code>:</p>
<blockquote><p>
This signal is emitted when a widget of this class is added to a scrolling aware parent, gtk_widget_set_scroll_adjustments() handles the emission. Implementation of this signal is optional.
</p></blockquote>
<p>This is not a signal name, but a signal ID<sup>1</sup> that has to be set in <a href="http://developer.gnome.org/doc/GGAD/z144.html">GtkWidgetClass</a><sup>2</sup>.</p>
<p>Some more documentation reading reveals that you can set this signal by using the <code>set_set_scroll_adjustments_signal</code> method on a widget:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> ScrollableWidget<span style="color: black;">&#40;</span>gtk.<span style="color: black;">DrawingArea</span><span style="color: black;">&#41;</span>:
    __gsignals__ = <span style="color: black;">&#123;</span>
        <span style="color: #483d8b;">&quot;set-scroll-adjustments&quot;</span>: <span style="color: black;">&#123;</span>
            gobject.<span style="color: black;">SIGNAL_RUN_LAST</span>,
            gobject.<span style="color: black;">TYPE_NONE</span>, <span style="color: black;">&#40;</span>gtk.<span style="color: black;">Adjustment</span>, gtk.<span style="color: black;">Adjustment</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>,
    <span style="color: black;">&#125;</span>
&nbsp;
    <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: black;">&#41;</span>:
        gtk.<span style="color: black;">DrawingArea</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">set_set_scroll_adjustments_signal</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;set-scroll-adjustments&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>It doesn&#8217;t really matter <em>how</em> you call the signal as long as it takes two arguments (the horizontal and vertical adjustment). This will make the method <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkwidget.html#method-gtkwidget--set-scroll-adjustments"><code>set_scroll_adjustments</code></a> (which you can&#8217;t override from within Python) return <em>True</em> when it is called and signal that the widget supports scrolling.</p>
<p>This, however, is only half the way, because the scrollable widget still needs the adjustments handed in via said methods. It&#8217;s of course possible to connect to the signal explicitly, but there&#8217;s an even more direct way by using action signals. </p>
<p>Action signals are the C programmer&#8217;s idea of &#8220;generic methods&#8221;. In order to create such a signal, it has to have the flag <code>gobject.SIGNAL_ACTION</code> and they are directly connected to a function which is then called on each signal emission. While in C, you have to provide a function pointer, in Python you can just implement functions with a compounded magic name<sup>3</sup> and have it called automatically. I haven&#8217;t found any documentation on that in the PyGObject or PyGTK docs, only some examples in the web:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> ScrollableWidget<span style="color: black;">&#40;</span>gtk.<span style="color: black;">DrawingArea</span><span style="color: black;">&#41;</span>:
    __gsignals__ = <span style="color: black;">&#123;</span>
        <span style="color: #483d8b;">&quot;set-scroll-adjustments&quot;</span>: <span style="color: black;">&#123;</span>
            gobject.<span style="color: black;">SIGNAL_RUN_LAST</span> | gobject.<span style="color: black;">SIGNAL_ACTION</span>, 
            gobject.<span style="color: black;">TYPE_NONE</span>, <span style="color: black;">&#40;</span>gtk.<span style="color: black;">Adjustment</span>, gtk.<span style="color: black;">Adjustment</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>,
    <span style="color: black;">&#125;</span>
&nbsp;
    <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: black;">&#41;</span>:
        gtk.<span style="color: black;">DrawingArea</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">set_set_scroll_adjustments_signal</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;set-scroll-adjustments&quot;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> do_set_scroll_adjustments<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, h_adjustment, v_adjustment<span style="color: black;">&#41;</span>:
         <span style="color: #808080; font-style: italic;"># do some useful stuff here, like saving them</span>
         ...</pre></div></div>

<p>The method being called on emission has to start with <code>do_</code>, following by the signal names with hyphens replaced by underscores.</p>
<p>The adjustment objects can then be configured to one&#8217;s own liking to have scroll bars show up or not. However, to know when the user did some scrolling, it&#8217;s necessary to listen on some signals:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">    <span style="color: #ff7700;font-weight:bold;">def</span> do_set_scroll_adjustments<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, h_adjustment, v_adjustment<span style="color: black;">&#41;</span>:
        h_adjustment.<span style="color: black;">connect</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;value-changed&quot;</span>, <span style="color: #008000;">self</span>._scroll_value_changed<span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>._hadj = h_adjustment
        v_adjustment.<span style="color: black;">connect</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;value-changed&quot;</span>, <span style="color: #008000;">self</span>._scroll_value_changed<span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>._vadj = v_adjustment</pre></div></div>

<p>To make the scroll bar show up, modify <code>upper</code>, <code>lower</code> and <code>page_size</code> on the adjustments.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #008000;">self</span>._hadj.<span style="color: black;">lower</span> = <span style="color: #ff4500;">0</span>
<span style="color: #008000;">self</span>._hadj.<span style="color: black;">upper</span> = <span style="color: #ff4500;">50</span>
<span style="color: #008000;">self</span>._hadj.<span style="color: black;">page_size</span> = <span style="color: #ff4500;">10</span></pre></div></div>

<p>This tells the scrollbar that the size of the underlying picture (<code>upper - lower</code>) is 50, while the visible size (<code>page_size</code>) is 10. </p>
<p>The page size obviously depends on the current size of the widget, which can be retrieved from the underlying <code>gtk.gdk.Window</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">width, height = <span style="color: #008000;">self</span>.<span style="color: black;">window</span>.<span style="color: black;">get_size</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The current position of the scroll bar is controlled by the property <code>value</code> of the adjustment object and should be in the range <code>[lower .. upper - page_size]</code>. Whenever the property is changed, the <code>value-changed</code> signal is emitted, which we&#8217;ve connected to previously, and the widget can be repainted.</p>
<p>If you&#8217;re curious, you can also see the whole gloriousness in <a href="http://www.cl.uzh.ch/kitt/hg/sta/torsten/file/dc2c113ef300/STA/app/ui/gtktreeview.py#l199">actual working code</a>.</p>
<ol class="footnotes"><li id="footnote_0_178" class="footnote">which you usually don&#8217;t seen when coding with PyGTK</li><li id="footnote_1_178" class="footnote">ditto</li><li id="footnote_2_178" class="footnote">a technique which I thoroughly dislike and should be converted to be used with decorators</li></ol>]]></content:encoded>
			<wfw:commentRss>http://shlomme.diotavelli.net/2009/05/17/scrollable-widgets-with-pygtk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I have no life and I must program</title>
		<link>http://shlomme.diotavelli.net/2008/05/31/i-have-no-life-and-i-must-program/</link>
		<comments>http://shlomme.diotavelli.net/2008/05/31/i-have-no-life-and-i-must-program/#comments</comments>
		<pubDate>Sat, 31 May 2008 10:44:53 +0000</pubDate>
		<dc:creator>shlomme</dc:creator>
				<category><![CDATA[coli]]></category>
		<category><![CDATA[lang:en]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://shlomme.diotavelli.net/?p=91</guid>
		<description><![CDATA[Some participants of this semester&#8217;s „Computational Linguistics” course (which is a code word for „10 different lecturers guide you through the wonderful world of algorithms and theoretical foundations of CoLi”) obviously lack a life and willfully extended their own homework assignment, writing small toolkits for finite state automata.
Surprisingly, all those toolkits were written in Python [...]]]></description>
			<content:encoded><![CDATA[<p>Some participants of this semester&#8217;s „Computational Linguistics” course (which is a code word for „10 different lecturers guide you through the wonderful world of algorithms and theoretical foundations of CoLi”) obviously lack a life and willfully extended their own homework assignment, writing small toolkits for finite state automata.</p>
<p>Surprisingly, all those toolkits were written in Python and made our C++-affine lecturer wonder if he probably should look into this language some more, apart from suggesting that we „maybe […] should get a life.”</p>
<p>So what does my toolkit do?</p>
<ul>
<li>Determinization of NFSAs to DFSAs</li>
<li>Creation of DFAs from simple regular expressions</li>
<li>Application of FSTs</li>
<li>dot graph output for *FSAs</li>
</ul>
<p>All in all, not very impressive, and not very hard. Still, if you like <a href="http://pyparsing.wikispaces.com/">PyParsing</a> and generator-expression-prone Python code, you might want to have look at <a href="http://diotavelli.net/files/tinyfst.tar.bz2">the TinyFST code</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://shlomme.diotavelli.net/2008/05/31/i-have-no-life-and-i-must-program/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Look at me, I know Functional Programming!</title>
		<link>http://shlomme.diotavelli.net/2008/05/05/look-at-me-i-know-functional-programming/</link>
		<comments>http://shlomme.diotavelli.net/2008/05/05/look-at-me-i-know-functional-programming/#comments</comments>
		<pubDate>Mon, 05 May 2008 20:22:14 +0000</pubDate>
		<dc:creator>shlomme</dc:creator>
				<category><![CDATA[lang:en]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://shlomme.diotavelli.net/2008/05/05/look-at-me-i-know-functional-programming/</guid>
		<description><![CDATA[Sometimes I wonder what the hell I might have been thinking while writing code like this1 :

1
2
3
4
5
6
7
def uncurry&#40;f&#41;:
    return lambda t: f&#40;*t&#41;
&#160;
def longest_common_prefix&#40;Sa, Sb&#41;:
    return len&#40;list&#40;
        takewhile&#40;uncurry&#40;eq&#41;,
                [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes I wonder what the hell I might have been thinking while writing code like this<sup>1</sup> :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> uncurry<span style="color: black;">&#40;</span>f<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #ff7700;font-weight:bold;">lambda</span> t: f<span style="color: black;">&#40;</span><span style="color: #66cc66;">*</span>t<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> longest_common_prefix<span style="color: black;">&#40;</span>Sa, Sb<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #008000;">list</span><span style="color: black;">&#40;</span>
        takewhile<span style="color: black;">&#40;</span>uncurry<span style="color: black;">&#40;</span>eq<span style="color: black;">&#41;</span>,
                  izip<span style="color: black;">&#40;</span>Sa, Sb<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<ol class="footnotes"><li id="footnote_0_89" class="footnote">I bet the tenses are all wrong again.</li></ol>]]></content:encoded>
			<wfw:commentRss>http://shlomme.diotavelli.net/2008/05/05/look-at-me-i-know-functional-programming/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Random Python unittesting snippet #1</title>
		<link>http://shlomme.diotavelli.net/2007/12/18/random-python-unittesting-snippet-1/</link>
		<comments>http://shlomme.diotavelli.net/2007/12/18/random-python-unittesting-snippet-1/#comments</comments>
		<pubDate>Tue, 18 Dec 2007 00:24:01 +0000</pubDate>
		<dc:creator>shlomme</dc:creator>
				<category><![CDATA[lang:en]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://shlomme.diotavelli.net/2007/12/18/random-python-unittesting-snippet-1/</guid>
		<description><![CDATA[A small context manager for stating assertions about exceptions in Python unit tests:

@contextmanager
def assert_raises&#40;*exc_types&#41;:
    &#34;&#34;&#34;A context to ensure that an exception of a given type is thrown.
&#160;
    Instead of
&#160;
    @nose.tools.raises(ValueError)
    def test_that_raises():
        # ... lengthy setup
 [...]]]></description>
			<content:encoded><![CDATA[<p>A small context manager for stating assertions about exceptions in Python unit tests:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">@contextmanager
<span style="color: #ff7700;font-weight:bold;">def</span> assert_raises<span style="color: black;">&#40;</span><span style="color: #66cc66;">*</span>exc_types<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;&quot;A context to ensure that an exception of a given type is thrown.
&nbsp;
    Instead of
&nbsp;
    @nose.tools.raises(ValueError)
    def test_that_raises():
        # ... lengthy setup
        raise ValueError
&nbsp;
    you can write
&nbsp;
    def test_that_raises_at_the_end():
        # ... lengthy setup
        with assert_raises(ValueError):
            raise ValueError
&nbsp;
    to make the scope for catching exceptions as small as possible.
    &quot;&quot;&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        <span style="color: #ff7700;font-weight:bold;">yield</span>
    <span style="color: #ff7700;font-weight:bold;">except</span> exc_types:
        <span style="color: #ff7700;font-weight:bold;">pass</span>
    <span style="color: #ff7700;font-weight:bold;">except</span>:
        <span style="color: #ff7700;font-weight:bold;">raise</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        <span style="color: #ff7700;font-weight:bold;">raise</span> <span style="color: #008000;">AssertionError</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Failed to throw exception of type(s) %s.&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>
            <span style="color: #483d8b;">&quot;, &quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>exc_type.__name__ <span style="color: #ff7700;font-weight:bold;">for</span> exc_type <span style="color: #ff7700;font-weight:bold;">in</span> exc_types<span style="color: black;">&#41;</span>,<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://shlomme.diotavelli.net/2007/12/18/random-python-unittesting-snippet-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stockholm TreeAligner 0.8 „Gamla Stan” released</title>
		<link>http://shlomme.diotavelli.net/2007/12/13/stockholm-treealigner-08-%e2%80%9egamla-stan%e2%80%9d-released/</link>
		<comments>http://shlomme.diotavelli.net/2007/12/13/stockholm-treealigner-08-%e2%80%9egamla-stan%e2%80%9d-released/#comments</comments>
		<pubDate>Thu, 13 Dec 2007 00:14:10 +0000</pubDate>
		<dc:creator>shlomme</dc:creator>
				<category><![CDATA[coli]]></category>
		<category><![CDATA[lang:en]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[treealigner]]></category>

		<guid isPermaLink="false">http://shlomme.diotavelli.net/2007/12/13/stockholm-treealigner-08-%e2%80%9egamla-stan%e2%80%9d-released/</guid>
		<description><![CDATA[It&#8217;s only a couple of months late, but we&#8217;ve just released a new version of the Stockholm TreeAligner to an awed audience. This release features the prototype implementations of TIGERSearch and alignment queries, which will be perfected in the next release, due in March 2008.
For those who are wondering what kind of code name Gamla [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s only a couple of months late, but we&#8217;ve just released a new version of the <a href="http://dev.ling.su.se/treealigner">Stockholm TreeAligner</a> to an awed audience. This release features the prototype implementations of TIGERSearch and alignment queries, which will be perfected in the next release, due in March 2008.</p>
<p>For those who are wondering what kind of code name <a href="http://en.wikipedia.org/wiki/Gamla_Stan">Gamla Stan</a> is: STA releases are named after Stockholms subway stations.</p>
<p>Align your trees while the release is still hot!</p>
]]></content:encoded>
			<wfw:commentRss>http://shlomme.diotavelli.net/2007/12/13/stockholm-treealigner-08-%e2%80%9egamla-stan%e2%80%9d-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Truth itself</title>
		<link>http://shlomme.diotavelli.net/2007/12/08/71/</link>
		<comments>http://shlomme.diotavelli.net/2007/12/08/71/#comments</comments>
		<pubDate>Sat, 08 Dec 2007 13:54:47 +0000</pubDate>
		<dc:creator>shlomme</dc:creator>
				<category><![CDATA[lang:en]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://shlomme.diotavelli.net/2007/12/08/71/</guid>
		<description><![CDATA[As is the way with Python, it turns out that you can create the start of something useful in less that fifty lines of code.↪
I simply cannot confirm often enough how true that is.
]]></description>
			<content:encoded><![CDATA[<p><i>As is the way with Python, it turns out that you can create the start of something useful in less that fifty lines of code.</i><a href="http://www.voidspace.org.uk/python/articles/mocking.shtml">↪</a></p>
<p>I simply cannot confirm often enough how true that is.</p>
]]></content:encoded>
			<wfw:commentRss>http://shlomme.diotavelli.net/2007/12/08/71/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TLT 2007</title>
		<link>http://shlomme.diotavelli.net/2007/12/06/tlt-2007/</link>
		<comments>http://shlomme.diotavelli.net/2007/12/06/tlt-2007/#comments</comments>
		<pubDate>Thu, 06 Dec 2007 10:46:56 +0000</pubDate>
		<dc:creator>shlomme</dc:creator>
				<category><![CDATA[coli]]></category>
		<category><![CDATA[lang:de]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://shlomme.diotavelli.net/2007/12/06/tlt-2007/</guid>
		<description><![CDATA[Es ist soweit, und die ganze Welt der Baumdatenbanken bekommt einen Geschmack vom Stockholm TreeAligner. Joakim wird morgen ein Poster über das „Gamla Stan”-Release von STA präsentieren (Paper).
Nachdem das Release nur ein paar Monate verspätet war, machen wir uns auch gerade daran, die technische Basis mit ein paar gezielten geradezurücken. Die Hauptattraktionen für das nächste [...]]]></description>
			<content:encoded><![CDATA[<p>Es ist soweit, und die ganze Welt der Baumdatenbanken bekommt einen Geschmack vom <a href="http://dev.ling.su.se/treealigner">Stockholm TreeAligner</a>. Joakim wird morgen ein Poster über das „Gamla Stan”-Release von STA präsentieren (<a href="http://tlt07.uib.no/papers/18.pdf">Paper</a>).</p>
<p>Nachdem das Release nur ein paar Monate verspätet war, machen wir uns auch gerade daran, die technische Basis mit ein paar gezielten geradezurücken. Die Hauptattraktionen für das nächste Release (Codename „Solna”, geplant für Mitte März) sollen Diff-Views für verschiedene Versionen eines Korpus und eine verbesserte &amp; erweiterte Suche per TSQL (TigerSearch, für einzelne Baumdatenbanken) und AQL (Alignment Query Language, für parallele Baumdatenbanken).</p>
<p>Helfer werden natürlich immer gebraucht – bei entsprechenden Programmierkenntnissen oder Interesse reicht eine Email; Arbeit gibt es genug!.</p>
]]></content:encoded>
			<wfw:commentRss>http://shlomme.diotavelli.net/2007/12/06/tlt-2007/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I have two cores, where&#8217;s my free lunch?</title>
		<link>http://shlomme.diotavelli.net/2007/08/26/i-have-two-cores-wheres-my-free-lunch/</link>
		<comments>http://shlomme.diotavelli.net/2007/08/26/i-have-two-cores-wheres-my-free-lunch/#comments</comments>
		<pubDate>Sat, 25 Aug 2007 22:38:55 +0000</pubDate>
		<dc:creator>shlomme</dc:creator>
				<category><![CDATA[lang:en]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tech]]></category>

		<guid isPermaLink="false">http://shlomme.diotavelli.net/2007/08/26/i-have-two-cores-wheres-my-free-lunch/</guid>
		<description><![CDATA[I have tried to optimize the TigerXML parser in STA [↪] a bit, the results (graphs are stored in memory, with a 55 MiB corpus, on my Core 2 Duo 2.2GHz):

unoptimized: 61.01s
optimized: 39.68s

That still seemed a bit too slow to me, and I decided to try out some parallelization: since the ID reference remapping and [...]]]></description>
			<content:encoded><![CDATA[<p>I have tried to optimize the TigerXML parser in STA [<a href="http://www.ling.su.se/dali/downloads/treealigner/index.htm">↪</a>] a bit, the results (graphs are stored in memory, with a 55 MiB corpus, on my Core 2 Duo 2.2GHz):</p>
<ul>
<li><b>unoptimized:</b> 61.01s</li>
<li><b>optimized:</b> 39.68s</li>
</ul>
<p>That still seemed a bit too slow to me, and I decided to try out some parallelization: since the ID reference remapping and graph store code in the parser is decoupled from parsing and the creation of the node data structures, I tried to put that into a separate thread. Both threads are mostly CPU-bound, so I quickly ran into the good old GIL problem. In short: in a Python process, only one thread my execute Python byte code at a time. This is not a problem if you are doing a lot of I/O or lurking around in message loops, but it&#8217;s deadly for CPU-bound tasks. It made the parser considerably slower, even when I used the shelve module instead of storing the graphs to memory (which involves a lot more disk I/O). </p>
<p>In times where multi-core CPUs are becoming a commodity, more fine-grained locking would be desirable in CPython, or, even better, more advanced types of parallelization support.</p>
<p>There are other approaches to parallel computing in Python readily available (based on forks, some with shared memory, some with pipes [<a href="http://wiki.python.org/moin/ParallelProcessing">↪</a>]), but they seem too heavyweight to be dragged in for this small problem: a non-trivial dependency just to shave off some seconds from the parsing process is not a good tradeoff.</p>
]]></content:encoded>
			<wfw:commentRss>http://shlomme.diotavelli.net/2007/08/26/i-have-two-cores-wheres-my-free-lunch/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Verweichlicht…</title>
		<link>http://shlomme.diotavelli.net/2007/08/16/verweichlicht%e2%80%a6/</link>
		<comments>http://shlomme.diotavelli.net/2007/08/16/verweichlicht%e2%80%a6/#comments</comments>
		<pubDate>Thu, 16 Aug 2007 00:07:07 +0000</pubDate>
		<dc:creator>shlomme</dc:creator>
				<category><![CDATA[lang:de]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tech]]></category>

		<guid isPermaLink="false">http://shlomme.diotavelli.net/2007/08/16/verweichlicht%e2%80%a6/</guid>
		<description><![CDATA[Die IDE an sich
Nach einem Jahr verschärftem Toolmonkeyism auf der Arbeit bin ich zu der Überzeugung gelangt, dass auch beim Python-Programmieren ein wenig IDE-Unterstützung nicht schlecht wäre. Eclipse (besonders das erstaunlich stabile 3.3) wächst einem dann doch ans Herz. Nicht dass ich für Python unbedingt Ctrl-1 bräuchte (z.b. den infernalischen Java-Typinferenz-Hack, Variablen ohne Typ zu [...]]]></description>
			<content:encoded><![CDATA[<h2>Die IDE an sich</h2>
<p>Nach einem Jahr verschärftem Toolmonkeyism auf der Arbeit bin ich zu der Überzeugung gelangt, dass auch beim Python-Programmieren ein wenig IDE-Unterstützung nicht schlecht wäre. Eclipse (besonders das erstaunlich stabile 3.3) wächst einem dann doch ans Herz. Nicht dass ich für Python unbedingt Ctrl-1 bräuchte (z.b. den infernalischen Java-Typinferenz-Hack, Variablen ohne Typ zu deklarieren und sich per Tastendruck den Typ hinschreiben zu lassen – geht leider nicht in new-style For-Schleifen!), aber Refactoring-Support wäre schon was feines. </p>
<h2>Refactoring in Python</h2>
<p>Natürlich ist Refactoring in Python beliebig schwierig und der <a href="http://bicyclerepair.sourceforge.net/">Bicycle Repair Main</a> verhaut den Code teilweise schon ziemlich. Aber „Extract Method”, „Inline Variable”, „Extract Local Variable” und ähnlich einfache Sachen sollten durchaus zu machen sein, solange man keinen Unfug mit <tt>locals()</tt>, <tt>globals()</tt>, <tt>__dict__</tt> oder <tt>(get|set|has)attr(...)</tt> macht. Und wenn man auf dieser Ebene programmiert, sollte man wissen, dass man sich mit automatischen Refactorings vielleicht nicht unbedingt nur Freude ins Haus holt. </p>
<h2>Python-IDEs</h2>
<p>In Zuge des TreeAligner-Workshops habe ich tatsächlich wieder mal ernstzunehmend Python programmiert. Um die ganze Sache etwas lehrreicher zu gestalten (<a href="http://pyparsing.wikispaces.com/">PyParsing</a> ist zwar nett, aber nicht mehr neu!) habe ich mich entschlossen, den Emacs zu verlassen und einige Python-IDEs auszuprobieren. Da ich <a href="http://www.die-offenbachs.de/eric/index.html">eric</a> schon zur Genüge kenne und auch nicht wirklich benutzbar finde, habe ich micht auf <a href="http://pydev.sourceforge.net/">Pydev 1.3.8</a> und <a href="http://wingware.com/">WingIDE 3.0.0b1</a> beschränkt.</p>
<h2>Das schlechte zuerst: Pydev</h2>
<p>Pydev ist wirklich erschreckend schlecht. Zwar hat man die üblichen Eclipse-Vorteile (run configurations etc.), aber dafür hat der Python-Editor keine Indentation-Engine: pro TAB-Taste wird einfach ein Level tiefer eingerückt, automatische Indentierung scheint nicht zu gehen. Das ist besonders nervig wenn man sich der datenzentrierten Programmierung verschrieben hat und andauernd große Dictionaries oder Listen als Literale im Code erstellt. Allein dieses Manko lässt Pydev schon aus dem Wettbewerb fallen.</p>
<p>Die automatische Code-Vervollständigung erschließt sich mir nicht wirklich, zumindest wird wohl die aktuelle Datei gescannt (das kann Emacs auch&#8230;). Die wenigen Refactorings, die Pydev unterstützt, scheinen aber zu funktionieren, wenigstens ein kleines Plus; insgesamt aber nicht überzeugend.</p>
<h2>Etwas besser: WingIDE 3.0</h2>
<p>WingIDE hat eine überraschend gute Code-Vervollständigung (alle Imports werden gescannt), auch Funktionsaufrufe auf Objekten werden vervollständigt, soweit WingIDE den Typ inferieren kann, ohne das Programm auszuführen. Der Editor ist gelungen und die Emacs-Emulation überzeugend. Die Indentation-Engine ist sehr gut und produziert bei tief verschachtelten Datenstrukturen subjektiv schönere Ergebnisse als der Emacs. </p>
<p>Der Debugger hat alles, was man erwartet, obwohl er manchmal etwas schneller reagieren könnte. Auch nervt, dass das Starten eines Debug-Laufes und das Weiterausführen nach einem Breakpoint ein Befehl sind. Alle anderen Zusammenstöße, die ich mit dem Debugger hatte, rechne ich meinem extravaganten Programmierstil zu.</p>
<p>WingIDE hat keinerlei Unterstützung für Refactorings, es sei denn, man versteht under „Rename Variable” eine Search/Replace-Operation. Für ein neues major release einer professionellen kommerziellen IDE im Jahr 2007 ein sehr schwaches Zeichen. Außerdem nerven einige kleine Bugs, die aber bei einer Beta-Version entschuldbar sind – von der Reaktion auf mein Feedback werde ich wohl eine Kaufentscheidung abhängig machen.</p>
<p>Einige Sache würde ich mich nur wünschen (z.b. ein ähnliches Feature wie <i>Quick Outline</i> in Eclipse). Darüber hinaus habe ich mir die Skriptbarkeit der IDE noch nicht angeschaut, und wie stark man sie tatsächlich erweitern kann. Unterstützung für <a href="http://codespeak.net/py/dist/test.html">py.test</a> wäre schon etwas, das man implementieren könnte.</p>
]]></content:encoded>
			<wfw:commentRss>http://shlomme.diotavelli.net/2007/08/16/verweichlicht%e2%80%a6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
