<?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>pyCurious</title>
	<atom:link href="http://pycurious.org/feed/" rel="self" type="application/rss+xml" />
	<link>http://pycurious.org</link>
	<description>for those curious about the dynamic side of life</description>
	<lastBuildDate>Thu, 22 Dec 2011 13:53:42 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>The Ultimate Python &#8211; LaTeX Environment</title>
		<link>http://pycurious.org/2011/12/the-ultimate-python-latex-environment/</link>
		<comments>http://pycurious.org/2011/12/the-ultimate-python-latex-environment/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 13:53:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://pycurious.org/?p=267</guid>
		<description><![CDATA[



Many times while creating LaTeX documents I&#8217;ve thought &#8220;Wouldn&#8217;t it be great if I could write an inline python script to generate some LaTeX code here.&#8221; In this post I describe how to embed python scripts in LaTeX, how to get Vim to correctly syntax highlight the embedded python, and the modifications required to get [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Style for vim syntax highlighting --></p>
<style type="text/css">
<!--
pre { padding: 6px; font-family: monospace; color: #000000; background-color: #ffffff; }
.Comment { color: #0000ff; }
.Constant { color: #ff00ff; }
.Identifier { color: #008b8b; }
.Type { color: #2e8b57; font-weight: bold; }
.PreProc { color: #a020f0; }
.Special { color: #6a5acd; }
.Statement { color: #a52a2a; font-weight: bold; }
-->
</style>
<p>Many times while creating LaTeX documents I&#8217;ve thought &#8220;Wouldn&#8217;t it be great if I could write an inline python script to generate some LaTeX code here.&#8221; In this post I describe how to embed python scripts in LaTeX, how to get Vim to correctly syntax highlight the embedded python, and the modifications required to get rubber to compile LaTeX that uses python.sty. All of the code and scripts mentioned in this post are available on <a href="https://bitbucket.org/brotchie/python-sty/">bitbucket</a>.</p>
<p>I have already built a system where python generated .tex files are \input into my documents (script execution is managed by makefiles). I want to take this a step further&#8212;allowing python source to sit in a .tex file alongside LaTeX source.</p>
<p>In 2007 Martin R. Ehmsen released a LaTeX package <i>python.sty</i> that allows such python embedding. python.sty defines a new <i>python</i> environment in which arbitrary python code can be placed. Everything that is written to stdout by the embedded python code is interpreted as LaTeX in the final document.</p>
<p><img src="http://pycurious.org/wordpress/wp-content/uploads/2011/12/example1.png" alt="example1" title="example1" width="612" height="198" class="alignnone size-full wp-image-283" /></p>
<p>For example, this sequence of identity matrices is generated with the mixture of LaTeX and python code below.</p>
<div class="wp_syntax">
<pre>
<span class="Special">$</span><span class="Special">N </span><span class="Statement">\times</span><span class="Special"> N</span><span class="Special">$</span> element identity matrices for <span class="Special">$</span><span class="Special">N </span><span class="Statement">\in</span><span class="Special"> </span><span class="Special">\{</span><span class="Special">1,2,</span><span class="Statement">\ldots</span><span class="Special">,5</span><span class="Special">\}</span><span class="Special">$</span>:

<span class="Special">\begin{python}</span>
<span class="Statement">def</span> <span class="Identifier">identity</span>(n):
    <span class="Constant">&quot;&quot;&quot;</span>
<span class="Constant">    Generates and returns the LaTeX code for</span>
<span class="Constant">    a n x n identity matrix.</span>

<span class="Constant">    &quot;&quot;&quot;</span>
    <span class="Statement">return</span> <span class="Constant">'</span><span class="Special">\n</span><span class="Constant">'</span>.join([
        <span class="Constant">r'\left['</span>,
        <span class="Constant">r'\begin{array}{%s}'</span> % (n*<span class="Constant">'c'</span>,),
        <span class="Constant">'</span><span class="Special">\\\\</span><span class="Constant">'</span>.join(<span class="Constant">'&amp;'</span>.join(<span class="Constant">'1'</span> <span class="Statement">if</span> i==j <span class="Statement">else</span> <span class="Constant">'0'</span> <span class="Statement">for</span> j <span class="Statement">in</span> <span class="Identifier">range</span>(n))
                        <span class="Statement">for</span> i <span class="Statement">in</span> <span class="Identifier">range</span>(n)),
        <span class="Constant">r'\end{array}'</span>,
        <span class="Constant">r'\right]'</span>,
    ])

<span class="Comment"># Displays identity matrices for</span>
<span class="Comment"># n \in {1, 2, ..., 5}.</span>
<span class="Identifier">print</span> <span class="Constant">'</span><span class="Special">\n</span><span class="Constant">'</span>.join([
    <span class="Constant">r'\begin{equation*}'</span>,
    <span class="Constant">r'\begin{array}{%s}'</span> % (<span class="Constant">5</span>*<span class="Constant">'c'</span>,),
    <span class="Constant">'&amp;'</span>.join(identity(i) <span class="Statement">for</span> i <span class="Statement">in</span> <span class="Identifier">range</span>(<span class="Constant">1</span>,<span class="Constant">6</span>)),
    <span class="Constant">r'\end{array}.'</span>,
    <span class="Constant">r'\end{equation*}'</span>,
])
<span class="Special">\end{python}</span>
</pre>
</div>
<h3>What improvements can we make to python.sty?</h3>
<p>By default when python.sty encounters <i>\begin{python}</i> the following actions are executed:</p>
<ol>
<li>All text up to the closing <i>\end{python}</i> is output to outfile.py; outfile is the basename of the .tex document being processed;</li>
<li>outfile.py is piped to the python executable with the resulting stdout and stderr stored to outfile.py.out and outfile.py.err;</li>
<li>outfile.py.out is included in the LaTeX document using <i>\input{outfile.py.out}</i>.</li>
</ol>
<p>This is great when a document contains a single python script, however since every environment overwrites outfile.py{.out,.err} it is impossible to view the python output and errors of all script executions. An <a href="https://bitbucket.org/brotchie/python-sty/src/tip/python.sty">updated python.sty</a> fixes this by writing each environment to a different outfileN.py where N is a counter that is incremented each environment.</p>
<p>The updated python.sty also stores python&#8217;s return code to outfileN.rc. If python fails with a return code other than 0 the traceback and any other stderr output is included with red text in the document.</p>
<p>For example, if we deliberately throw an exception the traceback is included in the document body.</p>
<div class="wp_syntax">
<pre>
<span class="Special">\begin{python}</span>
<span class="Comment"># Create a deliberate exception.</span>
<span class="Identifier">print</span> <span class="Constant">'This text will be displayed.'</span>
<span class="Identifier">print</span> <span class="Constant">1</span>/<span class="Constant">0</span>
<span class="Identifier">print</span> <span class="Constant">'This text won</span><span class="Special">\'</span><span class="Constant">t be displayed.'</span>
<span class="Special">\end{python}</span>
</pre>
</div>
<p><img src="http://pycurious.org/wordpress/wp-content/uploads/2011/12/example2.png" alt="example2" title="example2" width="542" height="130" class="alignnone size-full wp-image-294" /></p>
<h3>Can Vim correctly syntax highlight LaTeX embedded python?</h3>
<p>Python syntax-highlighted as LaTeX isn&#8217;t pretty. A stackoverflow <a href="http://stackoverflow.com/questions/5176972/trouble-using-vims-syn-include-and-syn-region-to-embed-syntax-highlighting">question and answer</a> describes how to get Vim to correctly highlight .tex as LaTeX while using the python syntax highlighter for \begin{python}\end{python} blocks. A condensed series of steps is</p>
<ol>
<li> Create a new Vim syntax file <i>~/.vim/syntax/pytex.vim</i> containing:
<pre>
" Syntax for LaTeX files with embedded Python
" environments.
let b:current_syntax = ''
unlet b:current_syntax
runtime! syntax/tex.vim

let b:current_syntax = ''
unlet b:current_syntax
syntax include @TeX syntax/tex.vim

let b:current_syntax = ''
unlet b:current_syntax
syntax include @Python syntax/python.vim
syntax region pythonCode matchgroup=Snip start="\\begin{python}" end="\\end{python}" containedin=@TeX contains=@Python

hi link Snip SpecialComment
let b:current_syntax = 'pytex'
    </pre>
</li>
<li>Add the following line to your <i>.vimrc</i>:
<pre>
    au BufRead *.tex set syntax=pytex
    </pre>
</li>
</ol>
<p>The LaTeX code snippits in this post were generated using this syntax highlighting setup and the <i>:TOhtml</i> command.</p>
<h3>Rubber can&#8217;t compile documents that use the python.sty package!</h3>
<p>Rubber is a python command line tool that greatly simplifies compiling LaTeX documents. Unfortunately it provides no simple way to pass additional command line arguments to the underlying latex and pdflatex executables.</p>
<p>python.sty uses the \write18 command that executes an arbitrary shell command from within LaTeX. This is, by default, restricted for security reasons. Full \write18 functionality can be enabled by passing the &#8211;shell-escape argument to latex or pdflatex.</p>
<p>I&#8217;ve created a <a href="https://code.launchpad.net/~brotchie/rubber/shell-escape">branch of Rubber</a> that accepts and passes on the &#8211;shell-escape command line argument. You should download and install this latest version if you wish to use Rubber in concert with python.sty.</p>
<p>With this shell-escape Rubber branch the example.tex file can be compiled using:</p>
<pre>
mkdir .build
rubber -d --shell-escape --into=.build example.tex
cp .build/example.pdf .
</pre>
<h3>Links of Interest</h3>
<ol>
<li><a href="https://bitbucket.org/brotchie/python-sty/">https://bitbucket.org/brotchie/python-sty/</a> &#8211; python.sty source, Vim syntax scripts, and an example .tex file.</li>
<li>
    <a href="http://stackoverflow.com/questions/5176972/trouble-using-vims-syn-include-and-syn-region-to-embed-syntax-highlighting">http://stackoverflow.com/questions/5176972/trouble-using-vims-syn-include-and-syn-region-to-embed-syntax-highlighting</a> &#8211; stackoverflow question detailing how to syntax python within LaTeX documents.</li>
<li> <a href="https://code.launchpad.net/~brotchie/rubber/shell-escape">https://code.launchpad.net/~brotchie/rubber/shell-escape</a> &#8211; shell-escape enabled branch of Rubber.</li>
<li> <a href="http://thewikiblog.appspot.com/blog/python-inside-latex">http://thewikiblog.appspot.com/blog/python-inside-latex</a> &#8211; where I found a copy of the original python.sty.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://pycurious.org/2011/12/the-ultimate-python-latex-environment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exporting KeepNote notebooks as FreeMind mind maps.</title>
		<link>http://pycurious.org/2011/11/exporting-keepnote-notebooks-as-freemind-mind-maps/</link>
		<comments>http://pycurious.org/2011/11/exporting-keepnote-notebooks-as-freemind-mind-maps/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 02:43:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://pycurious.org/?p=250</guid>
		<description><![CDATA[I heavily use KeepNote for taking random notes, keeping a daily journal, and managing a research pipeline. I&#8217;ve recently discovered the power of mind mapping with FreeMind, an open source mind mapping application. Out of curiosity I wanted to see what my KeepNote notebook looked like as a mind map.
KeepNote has an extension system and [...]]]></description>
			<content:encoded><![CDATA[<p>I heavily use <a href="http://keepnote.org">KeepNote</a> for taking random notes, keeping a daily journal, and managing a research pipeline. I&#8217;ve recently discovered the power of mind mapping with <a href="http://freemind.sourceforge.net/">FreeMind</a>, an open source mind mapping application. Out of curiosity I wanted to see what my KeepNote notebook looked like as a mind map.</p>
<p>KeepNote has an extension system and an easily navigable object hierarchy. I used the existing export_html extension as a base, adjusting the output to the FreeMind file format. The content of KeepNote notes are added as richcontent notes on the FreeMind nodes. Both KeepNote and FreeMind save notes in XHTML making the translation trivial.</p>
<p>The code is available at <a href="https://bitbucket.org/brotchie/export_freemind/overview">https://bitbucket.org/brotchie/export_freemind/overview</a>.</p>
<div class="wp-caption alignnone" style="width: 777px"><a href="https://bitbucket.org/brotchie/export_freemind/raw/default/images/export_freemind.png"><img alt="Export of my primary KeepNote notebook." src="https://bitbucket.org/brotchie/export_freemind/raw/default/images/export_freemind_small.png" title="Example Screenshot" width="767" height="480" /></a><p class="wp-caption-text">Export of my primary KeepNote notebook. KeepNote on left; resultant FreeMind mind map on right.</p></div>
]]></content:encoded>
			<wfw:commentRss>http://pycurious.org/2011/11/exporting-keepnote-notebooks-as-freemind-mind-maps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Two boost::mpl examples</title>
		<link>http://pycurious.org/2011/10/two-boostmpl-examples/</link>
		<comments>http://pycurious.org/2011/10/two-boostmpl-examples/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 11:06:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[boost]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[mpl]]></category>

		<guid isPermaLink="false">http://pycurious.org/?p=234</guid>
		<description><![CDATA[
Six months ago I indulged in some C++ metaprogramming hackery. I&#8217;d read through Abraham&#8217;s and Gurtovoy&#8217;s excellent book and wanted to try out some of their concepts. I recently found some of the code I&#8217;d written during this phase on paste bin. Here I present the two example with a brief description.
The first example implements [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://pycurious.org/wordpress/wp-content/uploads/2011/10/metaprogramming.png" alt="metaprogramming" title="metaprogramming" width="607" height="383" class="alignnone size-full wp-image-247" /></p>
<p>Six months ago I indulged in some C++ metaprogramming hackery. I&#8217;d read through <a href="http://www.amazon.com/Template-Metaprogramming-Concepts-Techniques-Beyond/dp/0321227255/ref=sr_1_1?ie=UTF8&#038;qid=1318935434&#038;sr=8-1">Abraham&#8217;s and Gurtovoy&#8217;s excellent book</a> and wanted to try out some of their concepts. I recently found some of the code I&#8217;d written during this phase on paste bin. Here I present the two example with a brief description.</p>
<p>The first example implements some contrived functionality that demonstrating the metaprogramming equivalents of vectors, maps, and iterators. The source is available at <a href="http://pastebin.com/UMPh6TuX">http://pastebin.com/UMPh6TuX</a>.</p>
<p>The second example brute forces problem 1 from <a href="http://projecteuler.net/problem=1">Project Euler</a> (the problem statement is repeated in the heading comment). The source is available at <a href="http://pastebin.com/NK9BMyz6">http://pastebin.com/NK9BMyz6</a>.</p>
<p><em>(Image source <a href="http://martinfowler.com/articles/rubyAtThoughtWorks.html">http://martinfowler.com/articles/rubyAtThoughtWorks.html</a>)</em></p>
]]></content:encoded>
			<wfw:commentRss>http://pycurious.org/2011/10/two-boostmpl-examples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scrolling with the Zoom Slider on a Microsoft Natural Ergonomic Desktop 7000 in Ubuntu</title>
		<link>http://pycurious.org/2011/08/scrolling-with-the-zoom-slider-on-an-microsoft-natural-ergonomic-desktop-7000-in-ubuntu/</link>
		<comments>http://pycurious.org/2011/08/scrolling-with-the-zoom-slider-on-an-microsoft-natural-ergonomic-desktop-7000-in-ubuntu/#comments</comments>
		<pubDate>Wed, 17 Aug 2011 09:10:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://pycurious.org/?p=219</guid>
		<description><![CDATA[The keyboard component of the Natural Ergonomic Desktop 7000 has a conveniently placed &#8220;zoom&#8221; slider in the centre. My desire to utilize this for scrolling web pages in Ubuntu lead me to some Google searching followed by downloading, patching, and compiling evrouter; a utility that allows you to transcode unhandled input events arriving from peripherals [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_218" class="wp-caption alignnone" style="width: 550px"><img src="http://pycurious.org/wordpress/wp-content/uploads/2011/08/mk_ned7000_large.jpg" alt="Microsoft Natural Ergonomic Desktop 7000" title="NED7000" width="540" height="310" class="size-full wp-image-218" /><p class="wp-caption-text">Microsoft Natural Ergonomic Desktop 7000</p></div>
<p>The keyboard component of the Natural Ergonomic Desktop 7000 has a conveniently placed &#8220;zoom&#8221; slider in the centre. My desire to utilize this for scrolling web pages in Ubuntu lead me to some Google searching followed by downloading, patching, and compiling evrouter; a utility that allows you to transcode unhandled input events arriving from peripherals into key codes and mouse actions more suitable for applications. The steps described in this post have been tested on Ubuntu 11.04 64bit, if you&#8217;re using an earlier version of Ubuntu YMMV.</p>
<p>The initial step is to download and install evrouter. For completeness here&#8217;s a copy-paste of my bash history whilst I was fetching, compiling, and installing evrouter(with large swathes of deletions).</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">cd</span> <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>tmp<span style="color: #000000; font-weight: bold;">/</span>
<span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">apt-get</span> <span style="color: #c20cb9; font-weight: bold;">install</span> git libxtst-dev
git clone https:<span style="color: #000000; font-weight: bold;">//</span>github.com<span style="color: #000000; font-weight: bold;">/</span>larsmagne<span style="color: #000000; font-weight: bold;">/</span>evrouter.git
<span style="color: #c20cb9; font-weight: bold;">wget</span> https:<span style="color: #000000; font-weight: bold;">//</span>raw.github.com<span style="color: #000000; font-weight: bold;">/</span>gist<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">754395</span><span style="color: #000000; font-weight: bold;">/</span>872183805da1da0b1d7703b0995dc755f8b815ad<span style="color: #000000; font-weight: bold;">/</span>evrouter-<span style="color: #000000;">0.4</span>_with_key_repeats_option.patch
<span style="color: #7a0874; font-weight: bold;">cd</span> evrouter
<span style="color: #c20cb9; font-weight: bold;">patch</span> <span style="color: #660033;">-p1</span> <span style="color: #000000; font-weight: bold;">&lt;</span>..<span style="color: #000000; font-weight: bold;">/</span>evrouter-<span style="color: #000000;">0.4</span>_with_key_repeats_option.patch
.<span style="color: #000000; font-weight: bold;">/</span>configure
<span style="color: #c20cb9; font-weight: bold;">make</span>
<span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">make</span> <span style="color: #c20cb9; font-weight: bold;">install</span></pre></td></tr></table></div>

<p>To do anything useful evrouter requires privileged access to devices linked to from /dev/input/by-id/. Adding<br />
<code><br />
**REPLACE WITH YOUR ACCOUNT NAME**   ALL=NOPASSWD: /usr/bin/evrouter<br />
</code></p>
<p>to the end of your /etc/sudoers file (remember to use visudo) will let your specific user account execute evrouter as root without a password.</p>
<p>We can ask evrouter to query all our connected input devices using</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> evrouter <span style="color: #660033;">-D</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>input<span style="color: #000000; font-weight: bold;">/</span>by-id<span style="color: #000000; font-weight: bold;">/*</span></pre></td></tr></table></div>

<p>Running this with 7000&#8217;s wireless dongle plugged in should display some resembling<br />
<code><br />
device  0: /dev/input/by-id/usb-Microsoft_Microsoft®_2.4GHz_Transceiver_V1.0-event-kbd: Microsoft Microsoft® 2.4GHz Transceiver V1.0<br />
device  1: /dev/input/by-id/usb-Microsoft_Microsoft®_2.4GHz_Transceiver_V1.0-event-mouse: Microsoft Microsoft® 2.4GHz Transceiver V1.0<br />
device  2: /dev/input/by-id/usb-Microsoft_Microsoft®_2.4GHz_Transceiver_V1.0-if01-event-mouse: Microsoft Microsoft® 2.4GHz Transceiver V1.0<br />
</code></p>
<p>Contrary to expectation the device that generates zoom sliders events is the event-mouse source<br />
<code><br />
/dev/input/by-id/usb-Microsoft_Microsoft®_2.4GHz_Transceiver_V1.0-event-mouse<br />
</code></p>
<p>All the events arriving from this device can be viewed in real-time using</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> evrouter <span style="color: #660033;">-d</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>input<span style="color: #000000; font-weight: bold;">/</span>by-id<span style="color: #000000; font-weight: bold;">/</span>usb-Microsoft_Microsoft®_2.4GHz_Transceiver_V1.0-event-mouse</pre></td></tr></table></div>

<p>which outputs<br />
<code><br />
Window "(null)": # Window title<br />
# Window "(null)": # Resource name<br />
# Window "(null)": # Class name<br />
"Microsoft Microsoft® 2.4GHz Transceiver V1.0" "/dev/input/by-id/usb-Microsoft_Microsoft®_2.4GHz_Transceiver_V1.0-event-mouse" none key/418 "fill this in!"</p>
<p>Window "(null)": # Window title<br />
# Window "(null)": # Resource name<br />
# Window "(null)": # Class name<br />
"Microsoft Microsoft® 2.4GHz Transceiver V1.0" "/dev/input/by-id/usb-Microsoft_Microsoft®_2.4GHz_Transceiver_V1.0-event-mouse" none key/419 "fill this in!"<br />
</code></p>
<p>as we zoom up and down. Given are some lines that we can paste directly into our ~/.evrouterrc config file, changing &#8220;fill this in!&#8221; to mouse-wheel up and down (XButton/4 and XButton/5)<br />
<code><br />
"Microsoft Microsoft® 2.4GHz Transceiver V1.0" "/dev/input/by-id/usb-Microsoft_Microsoft®_2.4GHz_Transceiver_V1.0-event-mouse" none key/418 "XButton/4"<br />
"Microsoft Microsoft® 2.4GHz Transceiver V1.0" "/dev/input/by-id/usb-Microsoft_Microsoft®_2.4GHz_Transceiver_V1.0-event-mouse" none key/419 "XButton/5"<br />
</code></p>
<p>With the above two lines in ~/.evrouterrc you should be able to start proxying zoom slides into mouse-wheel movements using</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> evrouter <span style="color: #660033;">-r</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>input<span style="color: #000000; font-weight: bold;">/</span>by-id<span style="color: #000000; font-weight: bold;">/</span>usb-Microsoft_Microsoft®_2.4GHz_Transceiver_V1.0-event-mouse</pre></td></tr></table></div>

<p>Happy scrolling!</p>
]]></content:encoded>
			<wfw:commentRss>http://pycurious.org/2011/08/scrolling-with-the-zoom-slider-on-an-microsoft-natural-ergonomic-desktop-7000-in-ubuntu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using python-purple with the twisted mainloop</title>
		<link>http://pycurious.org/2010/06/using-python-purple-with-the-twisted-mainloop/</link>
		<comments>http://pycurious.org/2010/06/using-python-purple-with-the-twisted-mainloop/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 02:26:53 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Cython]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://pycurious.org/?p=201</guid>
		<description><![CDATA[libpurple is the instant messaging library underlying the Pidgin and Adium multi-protocol IM clients. Out of the box libpurple supports a wide variety of protocols accessible via a consistent programmatic interface. The Carman project provides a set of python bindings for libpurple. The source for the bindings can be checked out from SVN at http://vcs.maemo.org/svn/carman/trunk/python-purple/.
The [...]]]></description>
			<content:encoded><![CDATA[<p>libpurple is the instant messaging library underlying the <a href="http://pidgin.im">Pidgin</a> and <a href="http://adium.im">Adium</a> multi-protocol IM clients. Out of the box libpurple supports a wide variety of protocols accessible via a consistent programmatic interface. The Carman project provides a set of python bindings for libpurple. The source for the bindings can be checked out from SVN at <a href="http://vcs.maemo.org/svn/carman/trunk/python-purple/">http://vcs.maemo.org/svn/carman/trunk/python-purple/</a>.</p>
<p>The python-purple bindings are provided as a set of .pyx files that must be compiled into a Python module using Cython. Instructions on compiling the module are available at <a href="http://briglia.net/wiki/tiki-index.php?page=Python-purple+Howto">http://briglia.net/wiki/tiki-index.php?page=Python-purple+Howto</a>. Although the instructions mention Python 2.5, they work fine when Python 2.6 is used.</p>
<p>The trunk version of the python-purple bindings utilizes python-ecore (a python abstraction of the core libraries used by Enlightenment) to manage the main loop. If you wish to use the twisted mainloop instead simply apply the following patch (<a href="/python-purple-twisted.patch">python-purple-twisted.patch</a>) and recompile the module.</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">Index: python-purple/purple.pyx
===================================================================
<span style="color: #888822;">--- python-purple/purple.pyx	<span style="">&#40;</span>revision <span style="">2088</span><span style="">&#41;</span></span>
<span style="color: #888822;">+++ python-purple/purple.pyx	<span style="">&#40;</span>working copy<span style="">&#41;</span></span>
<span style="color: #440088;">@@ -<span style="">22</span>,<span style="">8</span> +<span style="">22</span>,<span style="">8</span> @@</span>
 cdef extern from &quot;c_purple.h&quot;:
     glib.guint glib_input_add<span style="">&#40;</span>glib.gint fd, eventloop.PurpleInputCondition condition, eventloop.PurpleInputFunction function, glib.gpointer data<span style="">&#41;</span>
&nbsp;
<span style="color: #991111;">-import ecore</span>
 import signal
<span style="color: #00b000;">+from twisted.internet import reactor</span>
&nbsp;
 cdef glib.GHashTable *c_ui_info
&nbsp;
<span style="color: #440088;">@@ -<span style="">91</span>,<span style="">8</span> +<span style="">91</span>,<span style="">8</span> @@</span>
         if default_path:
             util.purple_util_set_user_dir<span style="">&#40;</span>default_path<span style="">&#41;</span>
&nbsp;
<span style="color: #991111;">-        # adds glib iteration inside ecore main loop</span>
<span style="color: #991111;">-        ecore.timer_add<span style="">&#40;</span><span style="">0.001</span>, self.__glib_iteration_when_idle<span style="">&#41;</span></span>
<span style="color: #00b000;">+        # adds glib iteration inside twisted main loop</span>
<span style="color: #00b000;">+        reactor.callLater<span style="">&#40;</span><span style="">0.001</span>, self.__glib_iteration_when_idle<span style="">&#41;</span></span>
&nbsp;
         # libpurple's built-in DNS resolution forks processes to perform
         # blocking lookups without blocking the main process.  It does not
<span style="color: #440088;">@@ -<span style="">171</span>,<span style="">7</span> +<span style="">171</span>,<span style="">7</span> @@</span>
&nbsp;
     def __glib_iteration_when_idle<span style="">&#40;</span>self<span style="">&#41;</span>:
         glib.g_main_context_iteration<span style="">&#40;</span>NULL, False<span style="">&#41;</span>
<span style="color: #991111;">-        return True</span>
<span style="color: #00b000;">+        reactor.callLater<span style="">&#40;</span><span style="">0.001</span>, self.__glib_iteration_when_idle<span style="">&#41;</span></span>
&nbsp;
     def purple_init<span style="">&#40;</span>self<span style="">&#41;</span>:
         '''Initializes the purple.
Index: python-purple/conversation_cbs.pxd
===================================================================
<span style="color: #888822;">--- python-purple/conversation_cbs.pxd	<span style="">&#40;</span>revision <span style="">2088</span><span style="">&#41;</span></span>
<span style="color: #888822;">+++ python-purple/conversation_cbs.pxd	<span style="">&#40;</span>working copy<span style="">&#41;</span></span>
<span style="color: #440088;">@@ -<span style="">104</span>,<span style="">7</span> +<span style="">104</span>,<span style="">7</span> @@</span>
         message = None
&nbsp;
     # FIXME: Maybe we need add more purple flags in the future
<span style="color: #991111;">-    if flags &amp; conversation.PURPLE_MESSAGE_SEND:</span>
<span style="color: #00b000;">+    if int<span style="">&#40;</span>flags<span style="">&#41;</span> &amp; conversation.PURPLE_MESSAGE_SEND:</span>
         flag = &quot;SEND&quot;
     else:
         flag = &quot;RECV&quot;
Index: python-purple/nullclient.py
===================================================================
<span style="color: #888822;">--- python-purple/nullclient.py	<span style="">&#40;</span>revision <span style="">2088</span><span style="">&#41;</span></span>
<span style="color: #888822;">+++ python-purple/nullclient.py	<span style="">&#40;</span>working copy<span style="">&#41;</span></span>
<span style="color: #440088;">@@ -<span style="">17</span>,<span style="">7</span> +<span style="">17</span>,<span style="">7</span> @@</span>
 #  along with this program.  If not, see &lt;http://www.gnu.org/licenses/&gt;.
 #
&nbsp;
<span style="color: #991111;">-import ecore</span>
<span style="color: #00b000;">+from twisted.internet import reactor</span>
 import getpass
 import purple
 import sys
<span style="color: #440088;">@@ -<span style="">60</span>,<span style="">5</span> +<span style="">60</span>,<span style="">7</span> @@</span>
     # Enable account <span style="">&#40;</span>connects automatically<span style="">&#41;</span>
     account.set_enabled<span style="">&#40;</span>True<span style="">&#41;</span>
&nbsp;
<span style="color: #991111;">-    # Initializes ecore mainloop</span>
<span style="color: #991111;">-    ecore.main_loop_begin<span style="">&#40;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+    # Start twisted mainloop</span>
<span style="color: #00b000;">+    reactor.run<span style="">&#40;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://pycurious.org/2010/06/using-python-purple-with-the-twisted-mainloop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using additional term structure interpolation methods with QuantLib&#8217;s Python bindings</title>
		<link>http://pycurious.org/2010/02/using-additional-term-structure-interpolation-methods-with-quantlibs-python-bindings/</link>
		<comments>http://pycurious.org/2010/02/using-additional-term-structure-interpolation-methods-with-quantlibs-python-bindings/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 10:05:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[QuantLib]]></category>
		<category><![CDATA[SWIG]]></category>

		<guid isPermaLink="false">http://pycurious.org/?p=178</guid>
		<description><![CDATA[The amazingly comprehensive open-source quantitative finance library QuantLib supplies a set of Python bindings generated with SWIG. Unfortunately much of QuantLib&#8217;s adaptability is made available via C++ templates. With the current SWIG wrapper it&#8217;s difficult to expose the entirety of QuantLib&#8217;s functionality without compiling every permutation of template parameter.
I discovered this quirk whilst trying to [...]]]></description>
			<content:encoded><![CDATA[<p>The amazingly comprehensive open-source quantitative finance library QuantLib supplies a set of Python bindings generated with SWIG. Unfortunately much of QuantLib&#8217;s adaptability is made available via C++ templates. With the current SWIG wrapper it&#8217;s difficult to expose the entirety of QuantLib&#8217;s functionality without compiling every permutation of template parameter.</p>
<p>I discovered this quirk whilst trying to apply cubic spline interpolation to a zero curve. It turns out that by default the SWIG interface only exposes a linearly interpolated zero curve class. Fortunately there are some nice macros within the SWIG interface that ease the exposure of additional interpolation schemes, albeit with a recompile of the Python module.</p>
<p>Zero curves with additional interpolation methods can be added to the end of <strong>QuantLib-SWIG-0.9.7/SWIG/zerocurve.i</strong> using the <strong>export_zero_curve</strong> macro as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">export_zero_curve<span style="color: #009900;">&#40;</span>ZeroCurve<span style="color: #339933;">,</span>Linear<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
export_zero_curve<span style="color: #009900;">&#40;</span>CubicZeroCurve<span style="color: #339933;">,</span>Cubic<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>After recompiling the Python bindings you&#8217;ll now have a <strong>CubicZeroCurve</strong> class that performs cubic spline interpolation between data points.</p>
<p>This approach can be used throughout much of the SWIG interface files to expose template customized QuantLib classes.</p>
]]></content:encoded>
			<wfw:commentRss>http://pycurious.org/2010/02/using-additional-term-structure-interpolation-methods-with-quantlibs-python-bindings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solution to Mercurial repository hooks not being run when served over http</title>
		<link>http://pycurious.org/2009/12/solution-to-mercurial-repository-hooks-not-being-run-when-served-over-http/</link>
		<comments>http://pycurious.org/2009/12/solution-to-mercurial-repository-hooks-not-being-run-when-served-over-http/#comments</comments>
		<pubDate>Wed, 09 Dec 2009 03:32:13 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Mercurial]]></category>
		<category><![CDATA[hg]]></category>

		<guid isPermaLink="false">http://pycurious.org/?p=163</guid>
		<description><![CDATA[At work we use trac for feature planning and defect management. Having recently moved from Subversion to Mercurial (Hg) we needed to install hooks in our Hg repositories so that trac tickets could be modified and closed via special commit messages commands.
Hooks are added to a repository&#8217;s configuration file (.hg/hgrc) as follows

[hooks]
incoming = /usr/bin/trac-admin /trac/project/directory [...]]]></description>
			<content:encoded><![CDATA[<p>At work we use <a href="http://trac.edgewall.org/">trac</a> for feature planning and defect management. Having recently moved from Subversion to <a href="http://mercurial.selenic.com/">Mercurial</a> (Hg) we needed to install hooks in our Hg repositories so that trac tickets could be modified and closed via special commit messages commands.</p>
<p>Hooks are added to a repository&#8217;s configuration file (<code>.hg/hgrc</code>) as follows</p>
<pre>
[hooks]
incoming = /usr/bin/trac-admin /trac/project/directory added Reponame $HG_NODE
</pre>
<p>This repository is then served using hgwebdir running via Apache mod_wsgi. <code>hgwebdir.config</code> configures the repositories that are shown, their filesystem locations, permissions, etc. </p>
<p>For the life of me I couldn&#8217;t figure out why the trac incoming hook wasn&#8217;t running. After a lot of tail chasing and advice from #mercurial we discovered the solution. </p>
<p>It turns out that by default Hg will ignore <code>.hg/hgrc</code> files that aren&#8217;t owned by a trusted user. Since our repositories are 2775/664 root:apache and the server process only trusts <code>.hg/hgrc</code> files that it owns, all our repository specific config options are ignored.</p>
<p>Simple adding</p>
<pre>
[trusted]
users = root
</pre>
<p>to <code>hgweb.config</code> fixed the problem and our trac hooks now run as desired.</p>
]]></content:encoded>
			<wfw:commentRss>http://pycurious.org/2009/12/solution-to-mercurial-repository-hooks-not-being-run-when-served-over-http/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Passing Python file objects across a SWIG interface</title>
		<link>http://pycurious.org/2009/12/passing-python-file-objects-across-a-swig-interface/</link>
		<comments>http://pycurious.org/2009/12/passing-python-file-objects-across-a-swig-interface/#comments</comments>
		<pubDate>Fri, 04 Dec 2009 13:50:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[SWIG]]></category>
		<category><![CDATA[cpython]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://pycurious.org/?p=121</guid>
		<description><![CDATA[SWIG works great out of the box when you&#8217;re dealing with basic types. Once you start to wrap more complicated APIs the type conversion magic can only go so far. 
I have been writing a Python SWIG interface for a library that accepts stdio FILE* pointers for input/output. Here I&#8217;ll present a minimal example where [...]]]></description>
			<content:encoded><![CDATA[<p>SWIG works great out of the box when you&#8217;re dealing with basic types. Once you start to wrap more complicated APIs the type conversion magic can only go so far. </p>
<p>I have been writing a Python SWIG interface for a library that accepts stdio <code>FILE*</code> pointers for input/output. Here I&#8217;ll present a minimal example where a Python file object is passed as a <code>FILE*</code> to a simple C function. All source is available <a href="http://pycurious.org/hg/pycurious/fix/file/1f54edaaab02/basic/">here</a> if you wish to follow along.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">char</span> buffer<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1024</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">char</span><span style="color: #339933;">*</span>
message<span style="color: #009900;">&#40;</span>FILE <span style="color: #339933;">*</span>input<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    memset<span style="color: #009900;">&#40;</span>buffer<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>buffer<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    fread<span style="color: #009900;">&#40;</span>buffer<span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>buffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> input<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> buffer<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This simply reads from a file stream until it&#8217;s closed and returns what was read. I preemptively apologise for it not being thread safe.</p>
<p>We&#8217;ll create a module called <code>test</code> wrapping the C function <code>message</code> such that the following code (<a href="http://pycurious.org/hg/pycurious/fix/file/1f54edaaab02/basic/example.py">example.py</a>) will output <em>&#8220;Hello World&#8221;</em>.</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;">os</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">test</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Create and open pipe as file objects</span>
r,w = <span style="color: #dc143c;">os</span>.<span style="color: black;">pipe</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
fr, fw = <span style="color: #dc143c;">os</span>.<span style="color: black;">fdopen</span><span style="color: black;">&#40;</span>r, <span style="color: #483d8b;">'r'</span><span style="color: black;">&#41;</span>, <span style="color: #dc143c;">os</span>.<span style="color: black;">fdopen</span><span style="color: black;">&#40;</span>w, <span style="color: #483d8b;">'w'</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Write and close</span>
fw.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'Hello World'</span><span style="color: black;">&#41;</span>
fw.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Read data from pipe using test module</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #dc143c;">test</span>.<span style="color: black;">message</span><span style="color: black;">&#40;</span>fr<span style="color: black;">&#41;</span></pre></div></div>

<p>The first cut at a SWIG interface file yields</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">%</span>module test
<span style="color: #339933;">%</span><span style="color: #009900;">&#123;</span>
<span style="color: #339933;">#include &quot;test.h&quot;</span>
<span style="color: #339933;">%</span><span style="color: #009900;">&#125;</span>
<span style="color: #993333;">char</span> <span style="color: #339933;">*</span>message<span style="color: #009900;">&#40;</span>FILE <span style="color: #339933;">*</span>input<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Unfortunately when we build and run example.py we get a <code>TypeError</code> indicating the argument we passed couldn&#8217;t be converted to a <code>FILE*</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">$ python setup.<span style="color: black;">py</span> build_ext --inplace
$ python example.<span style="color: black;">py</span> 
Traceback <span style="color: black;">&#40;</span>most recent call last<span style="color: black;">&#41;</span>:
  File <span style="color: #483d8b;">&quot;example.py&quot;</span>, line <span style="color: #ff4500;">17</span>, <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #66cc66;">&lt;</span>module<span style="color: #66cc66;">&gt;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #dc143c;">test</span>.<span style="color: black;">message</span><span style="color: black;">&#40;</span>fr<span style="color: black;">&#41;</span>
<span style="color: #008000;">TypeError</span>: <span style="color: #ff7700;font-weight:bold;">in</span> method <span style="color: #483d8b;">'message'</span>, argument <span style="color: #ff4500;">1</span> of <span style="color: #008000;">type</span> <span style="color: #483d8b;">'FILE *'</span></pre></div></div>

<p>How do we make SWIG correctly convert the Python file type to a <code>FILE*</code>? The solution lies in a SWIG feature called a typemap.</p>
<p>Typemaps allow you to write short stubs in C to convert objects from Python to C and vice-versa. Writing them requires you to have some knowledge of the Python API, for simple conversions however you can make good progress simply by digging through the Python include directory.</p>
<p>Adding the following typemap to our SWIG interface file tells squid how to convert incoming Python objects into <code>FILE*</code> pointers. Conveniently the Python C API provides the <code>PyFile_Check</code> function that checks if a <code>PyObject*</code> is of the PyFile type and <code>PyFile_AsFile</code> functions that returns a <code>FILE*</code> given a PyFile instance.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* Converts a PyFile instance to a stdio FILE* */</span>
<span style="color: #339933;">%</span>typemap<span style="color: #009900;">&#40;</span>in<span style="color: #009900;">&#41;</span> FILE<span style="color: #339933;">*</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> PyFile_Check<span style="color: #009900;">&#40;</span>$input<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        $<span style="color: #0000dd;">1</span> <span style="color: #339933;">=</span> PyFile_AsFile<span style="color: #009900;">&#40;</span>$input<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
        PyErr_SetString<span style="color: #009900;">&#40;</span>PyExc_TypeError<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;$1_name must be a file type.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> NULL<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now when we build test and run example.py we get the desired result.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">$ python example.<span style="color: black;">py</span> 
Hello World</pre></div></div>

<p>Notice that if we pass a non-file type to <code>message</code> a <code>TypeError</code> will be raised.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">test</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #dc143c;">test</span>.<span style="color: black;">message</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'not a file'</span><span style="color: black;">&#41;</span>
Traceback <span style="color: black;">&#40;</span>most recent call last<span style="color: black;">&#41;</span>:
  File <span style="color: #483d8b;">&quot;&lt;stdin&gt;&quot;</span>, line <span style="color: #ff4500;">1</span>, <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #66cc66;">&lt;</span>module<span style="color: #66cc66;">&gt;</span>
<span style="color: #008000;">TypeError</span>: <span style="color: #008000;">input</span> must be a <span style="color: #008000;">file</span> <span style="color: #008000;">type</span>.</pre></div></div>

<p>This simple example demonstrates one powerful feature of SWIG that can be expanded to wrap complex C and even C++ APIs.</p>
]]></content:encoded>
			<wfw:commentRss>http://pycurious.org/2009/12/passing-python-file-objects-across-a-swig-interface/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Forget functions: A class based approach to Python decorators</title>
		<link>http://pycurious.org/2009/11/forget-functions-a-class-based-approach-to-python-decorators/</link>
		<comments>http://pycurious.org/2009/11/forget-functions-a-class-based-approach-to-python-decorators/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 12:07:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://pycurious.org/?p=54</guid>
		<description><![CDATA[A decorator is simple syntactic sugar for applying a transformation to a function or method. Both

class A&#40;object&#41;:
    @decorator
    def name&#40;self&#41;:
        return &#34;foo&#34;

and

class A&#40;object&#41;:
    def name&#40;self&#41;:
        return &#34;foo&#34;
    name = [...]]]></description>
			<content:encoded><![CDATA[<p>A decorator is simple syntactic sugar for applying a transformation to a function or method. 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> A<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    @decorator
    <span style="color: #ff7700;font-weight:bold;">def</span> name<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;">return</span> <span style="color: #483d8b;">&quot;foo&quot;</span></pre></div></div>

<p>and</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> A<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> name<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;">return</span> <span style="color: #483d8b;">&quot;foo&quot;</span>
    name = decorator<span style="color: black;">&#40;</span>name<span style="color: black;">&#41;</span></pre></div></div>

<p>are equivalent. The quintessential decorator example contains a function returning a closure that performs some transformation on the wrapped function&#8217;s return value. For example</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> upper<span style="color: black;">&#40;</span>wrapped<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> shim<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;"># convert returned value to upper case</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> wrapped<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>.<span style="color: black;">upper</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> shim
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> A<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    @upper
    <span style="color: #ff7700;font-weight:bold;">def</span> name<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;">return</span> <span style="color: #483d8b;">&quot;foo&quot;</span>
&nbsp;
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a = A<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">print</span> a.<span style="color: black;">name</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
FOO</pre></div></div>

<p>When you wish to create a decorator that accepts additional arguments such as</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> A<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    @expose<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;get_name&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> name<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;">return</span> <span style="color: #483d8b;">&quot;foo&quot;</span></pre></div></div>

<p>the hierarchy of closures can become complicated, and in my opinion unpythonic.</p>
<h3>Class based decorators with arguments</h3>
<p>Since a decorator can be any callable and we can override a class&#8217;s <em>__call__</em> method to emulate a function call, a <em>&#8220;decorator class&#8221;</em> can be constructed. This is nice because in the <em>_shim</em> we have access to both the decorator class instance (<em>self</em>) and the instance of the class containing the decorated method (<em>instance</em>).</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> expose<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>, name<span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>._name = name
        <span style="color: #008000;">self</span>._wrapped = <span style="color: #008000;">None</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> _shim<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, instance, <span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Special RPC handling for %s, %r, %r'</span> <span style="color: #66cc66;">%</span> \
            <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._name, args, kwargs<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._wrapped<span style="color: black;">&#40;</span>instance, <span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>
&nbsp;
    <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>, wrapped<span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>._wrapped = wrapped
        <span style="color: #ff7700;font-weight:bold;">def</span> shim<span style="color: black;">&#40;</span>instance, <span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._shim<span style="color: black;">&#40;</span>instance, <span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> shim
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> A<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    @expose<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;get_name&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> name<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;">return</span> <span style="color: #483d8b;">&quot;foo&quot;</span>
&nbsp;
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a = A<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">print</span> a.<span style="color: black;">name</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
Special RPC handling <span style="color: #ff7700;font-weight:bold;">for</span> get_name, <span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
foo</pre></div></div>

<h3>Class based decorators without arguments</h3>
<p>Expose handles the case where the decorator accepts arguments. But what if we just wanted to write</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> A<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    @expose
    <span style="color: #ff7700;font-weight:bold;">def</span> name<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;">return</span> <span style="color: #483d8b;">&quot;foo&quot;</span></pre></div></div>

<p>Since <em>expose</em> is now a class, its <em>__init__</em> method will be called with the method <em>name</em> as an argument. We cannot simply implement a <em>__call__</em> method on <em>expose</em> because we want to get hold of the decorated method&#8217;s containing class instance. The trick here is to change <em>expose</em> into a non-data descriptor by adding a <em>__get__</em> special method. This <em>__get__</em> is passed the decorator&#8217;s containing class instance, thus we create and return a closure that calls expose&#8217;s <em>_shim</em> method with the desired arguments.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> expose<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>, wrapped<span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>._wrapped = wrapped
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> _shim<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, instance, <span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Special RPC handling for %s, %r, %r'</span> <span style="color: #66cc66;">%</span> \
            <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._wrapped.__name__, args, kwargs<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._wrapped<span style="color: black;">&#40;</span>instance, <span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__get__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, instance, owner<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">def</span> shim<span style="color: black;">&#40;</span><span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._shim<span style="color: black;">&#40;</span>instance, <span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> shim
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> A<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    @expose
    <span style="color: #ff7700;font-weight:bold;">def</span> name<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;">return</span> <span style="color: #483d8b;">&quot;foo&quot;</span>
&nbsp;
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a = A<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">print</span> a.<span style="color: black;">name</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
Special RPC handling <span style="color: #ff7700;font-weight:bold;">for</span> name, <span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
foo</pre></div></div>

<h3>Generic class based decorator</h3>
<p>We can combine the two methods above to create a generic decorator base class that handles both the argument and no argument case. The implementation of <em>decorator_base</em> can be found <a href="http://pycurious.org/hg/examples/file/c603666c4b6b/basedecorator/decorator_base.py">here</a>. Below is an example where the <em>example</em> decorator class extends <em>decorator_base</em>.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> example<span style="color: black;">&#40;</span>decorator_base<span style="color: black;">&#41;</span>:
    default_positional_args = <span style="color: black;">&#40;</span><span style="color: #483d8b;">'Default Name'</span>,<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> _arg_init<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>,
                  name,
                  description=<span style="color: #483d8b;">&quot;Default Description&quot;</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>._name = name
        <span style="color: #008000;">self</span>._description = description
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> _shim<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, instance, <span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>._name, <span style="color: #008000;">self</span>._description, args, kwargs
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._wrapped<span style="color: black;">&#40;</span>instance, <span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Test<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    @example
    <span style="color: #ff7700;font-weight:bold;">def</span> upper<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, text<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> text.<span style="color: black;">upper</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    @example<span style="color: black;">&#40;</span><span style="color: #483d8b;">'Verbose Name'</span>, description=<span style="color: #483d8b;">'Verbose Description'</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> lower<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, text<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> text.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&gt;&gt;&gt;</span> t = Test<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">print</span> t.<span style="color: black;">upper</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'hElLo'</span><span style="color: black;">&#41;</span>
Default Name Default Description <span style="color: black;">&#40;</span><span style="color: #483d8b;">'hEllo'</span>,<span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
HELLO
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">print</span> t.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'HeLlO'</span><span style="color: black;">&#41;</span>
Verbose Name Verbose Description <span style="color: black;">&#40;</span><span style="color: #483d8b;">'HeLlO'</span>,<span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
hello</pre></div></div>

<p>An equivalent class based decorator can be constructed using metaclasses, this will be the subject of further post. I hope this post gives sheds some light on using classes to implement decorators. </p>
]]></content:encoded>
			<wfw:commentRss>http://pycurious.org/2009/11/forget-functions-a-class-based-approach-to-python-decorators/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Simple Python __metaclass__ example</title>
		<link>http://pycurious.org/2009/11/simple-python-__metaclass__-example/</link>
		<comments>http://pycurious.org/2009/11/simple-python-__metaclass__-example/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 03:16:14 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[metaclass]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://pycurious.org/?p=3</guid>
		<description><![CDATA[Metaclasses seem to be an obscure, misunderstood area of Python&#8217;s object model. Here is a simple example that I&#8217;ve used to both understand and explain what a metaclass is a how it can be used.
This code snippet was spawned from a colleague&#8217;s query.
&#8220;What would be the most pythonic way to override a class type&#8217;s string representation?&#8221;
Expressed in [...]]]></description>
			<content:encoded><![CDATA[<p>Metaclasses seem to be an obscure, misunderstood area of Python&#8217;s object model. Here is a simple example that I&#8217;ve used to both understand and explain what a metaclass is a how it can be used.</p>
<p>This code snippet was spawned from a colleague&#8217;s query.</p>
<p><em>&#8220;What would be the most pythonic way to override a class type&#8217;s string representation?&#8221;</em></p>
<p>Expressed in code he wanted a new-style class type <strong>A</strong> to behave like</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #66cc66;">&gt;&gt;&gt;</span> A
<span style="color: #66cc66;">&lt;</span>class <span style="color: #483d8b;">'__main__.A'</span><span style="color: #66cc66;">&gt;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>A<span style="color: black;">&#41;</span>
<span style="color: #483d8b;">'Hello World'</span></pre></div></div>

<p>Unfotunately overriding <strong>A</strong>&#8217;s <em>__str__</em> method</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">class</span> A<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;">__str__</span><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;">return</span> <span style="color: #483d8b;">&quot;Hello World&quot;</span>
... 
<span style="color: #66cc66;">&gt;&gt;&gt;</span> A
<span style="color: #66cc66;">&lt;</span>class <span style="color: #483d8b;">'__main__.A'</span><span style="color: #66cc66;">&gt;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>A<span style="color: black;">&#41;</span>
<span style="color: #483d8b;">&quot;&lt;class '__main__.A'&gt;&quot;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>A<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #483d8b;">'Hello World'</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span></pre></div></div>

<p>only overrides the string representation of instances of <strong>A</strong> rather than the type <strong>A</strong>. </p>
<p>The solution to the problem leads us to metaclasses. My colleague&#8217;s conundrum can be solved by creating a new-style class with base <em>type</em> and a <em>__str__</em> method. This acts to override the <em>__str__</em> method of <strong>A</strong>&#8217;s type rather than instances of <strong>A</strong>.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">class</span> meta_A<span style="color: black;">&#40;</span><span style="color: #008000;">type</span><span style="color: black;">&#41;</span>:
...  <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__str__</span><span style="color: black;">&#40;</span>cls<span style="color: black;">&#41;</span>:
...   <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">&quot;Hello World&quot;</span>
... 
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">class</span> A<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
...  <span style="color: #0000cd;">__metaclass__</span> = meta_A
... 
<span style="color: #66cc66;">&gt;&gt;&gt;</span> A
<span style="color: #66cc66;">&lt;</span>class <span style="color: #483d8b;">'__main__.A'</span><span style="color: #66cc66;">&gt;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>A<span style="color: black;">&#41;</span>
<span style="color: #483d8b;">'Hello World'</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>A<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #483d8b;">'&lt;__main__.A object at 0x10049e710&gt;'</span></pre></div></div>

<p>Thus we have a pythonic mechanism for overriding the string representation of a class type. </p>
<p>Note that there is new syntax in Python 3.0 for specifying a metaclass.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">class</span> A<span style="color: black;">&#40;</span>metaclass=meta_A<span style="color: black;">&#41;</span>:
...  <span style="color: #ff7700;font-weight:bold;">pass</span>
...</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://pycurious.org/2009/11/simple-python-__metaclass__-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
