<?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>jessenoller.com &#187; concurrency</title>
	<atom:link href="http://jessenoller.com/category/concurrency/feed/" rel="self" type="application/rss+xml" />
	<link>http://jessenoller.com</link>
	<description>python, programming and other things</description>
	<lastBuildDate>Wed, 11 Jan 2012 19:01:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Stackless: You got your coroutines in my subroutines.</title>
		<link>http://jessenoller.com/2009/02/23/stackless-you-got-your-coroutines-in-my-subroutines/</link>
		<comments>http://jessenoller.com/2009/02/23/stackless-you-got-your-coroutines-in-my-subroutines/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 20:43:33 +0000</pubDate>
		<dc:creator>jesse</dc:creator>
				<category><![CDATA[concurrency]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[pycon 2009]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://jessenoller.com/?p=495</guid>
		<description><![CDATA[Note:This is another post in what I hope will be a series leading up to my concurrency/distributed systems talk at PyCon. I'm steadily working through experimenting with and learning the various frameworks/libraries in the python ecosystem.

I reserve the right (and probably will) to revise these entries based on feedback from people (mainly the author(s) ...]]></description>
			<content:encoded><![CDATA[<p><b>Note:</b>This is another post in what I hope will be a series leading up to my concurrency/distributed systems talk at PyCon. I’m steadily working through experimenting with and learning the various frameworks/libraries in the python ecosystem.</p>
<p>I reserve the right (and probably will) to revise these entries based on feedback from people (mainly the author(s) of said tool(s)). I will also add additional bits and pieces as I learn and explore more.<b>/Note</b></p>
<p>Stackless python — here’s another big one on the pile — is much more than a library, or a framework which runs on CPython — Stackless is actually a  modified version of the CPython interpreter. It’s much more than just a C-extension. Stackless is in use by various people and companies — most notably, it’s in use by CCP Games, makers of Eve Online (see <a href="http://www.stackless.com/Members/rmtew/News%20Archive/newsPyCon2006Pres">this</a> pycon presentation). In fact, CCP Games is a large part of why Stackless is still around today.</p>
<p><span id="more-495"></span></p>
<p>I say that intentionally — quoting the readme in the Stackless/ directory of the distribution(<a href="http://svn.python.org/view/stackless/trunk/Stackless/readme.txt?view=markup" target="_blank">here</a>):</p>
<blockquote><p>
In 2003, the fabulous PyPy porject was started, which is still<br />
performing very well. I have implemented Stackless for PyPy<br />
(with lots of support from Armin), and it is so incredibly<br />
much nicer. No more fiddling with existing calling conventions,<br />
no compromizes, everything that needs to be stackless also is.</p>
<p>Unfortuantely, PyPy is still not fast and complete enough to<br />
take over. This means, my users are still whining for an update<br />
all the time CPython gets an update.<br />
And maintaining this code gets more and more a nightmare for<br />
me, since I have the nice PyPy version, and I hate hacking this<br />
clumsy C code again and again.
</p></blockquote>
<p>The original author, Christian Tismer largely moved onto PyPy, which is still largely in it infancy (although I read through bits of the code base frequently, it’s pretty), and further development has largely been stalled minus the improvements Richard M. Tew (CCP Games) and others have done. There’s still life in it.</p>
<p>Fundamentally, Stackless modifies the interpreter internals a bit to modify the way that the C call stack is manipulated/used as well as to add other other nice bits Stackless offers (<a href="http://en.wikipedia.org/wiki/Call_stack">call stack</a>). Stackless simply doesn’t use the C call stack — all told, each microthread only has a few kilobytes of overhead, which is awesome.</p>
<p>It adds something called microthreads and does other patching to python-core. Normal OS/Posix threads require a fair amount of resources to create and run — in the case of Python, each thread has to get its own stack, this costs memory. With Stackless’ microthread support — you get “threads”, but threads which cost a significantly less, and potentially execute faster due to context switching improvements (no need to go from user-&gt;kernel-&gt;user and so on).</p>
<p><b>Point of Order</b>: Before I continue, I want to clear up a common misconception I’ve heard — Stackless, does not in any way, remove the Global Interpreter Lock. No sir. It’s still there. Lurking. Waiting to steal your candy. Also, it still has a stack, so it’s not truly “stackless”.</p>
<p>So, microthreads are smaller and require less OS hand holding for context switching, and ultimately can (and are) scheduled by the interpreter, rather than the operating system.</p>
<p><b>install note for os/x users</b>: You need to pass the “–enable-stacklessfewerregisters” to configure, otherwise, make pukes on you.</p>
<p>Stackless is a basic implementation of these — for a simple resource example usage example, I wrote a simple script which spawns 2,000 threads (sorry windows) and 2,000 tasklets. I watched the memory usage of both:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p495code1'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4951"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p495code1"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">threading</span>
<span style="color: #ff7700;font-weight:bold;">def</span> func<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">120</span><span style="color: black;">&#41;</span>
&nbsp;
threads = <span style="color: black;">&#91;</span><span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#40;</span>target=func<span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2000</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> threads:
    i.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> threads:
    i.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>For the threaded script — the resident size was 42M and the virtual size was 1037. Versus the stackless version:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p495code2'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4952"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code" id="p495code2"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span>
<span style="color: #ff7700;font-weight:bold;">import</span> stackless
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> func<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">120</span><span style="color: black;">&#41;</span>:
        <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
        stackless.<span style="color: black;">schedule</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2000</span><span style="color: black;">&#41;</span>:
    stackless.<span style="color: black;">tasklet</span><span style="color: black;">&#40;</span>func<span style="color: black;">&#41;</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
stackless.<span style="color: black;">run</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>Stackless had a resident size of 3416K and a virtual size of 22M — virtually microscopic versus the heavier thread version. Obviously, they are not line for line comparisons — the Stackless version, like other cooperative multitasking systems requires that each tasklet be a good citizen, and not block execution forever, instead rescheduling itself or otherwise yielding to allow for others to run. If a tasklet blocks on a socket, everyone blocks on that tasklet.</p>
<p>Someone asked me to track the linear growth of the threaded numbers vs. the tasklet numbers. Since I’m a sucker, I thought I’d take him up on it (OS/X 10.5, 4GB of ram, Core 2 Duo):</p>
<p><b>Threads</b>:</p>
<table border="1">
<th>Num Threads</th>
<th>Resident Size</th>
<th>Virtual Size</th>
<tr>
<td>2</td>
<td>3412K</td>
<td>23M</td>
</tr>
<tr>
<td>200</td>
<td>7336K</td>
<td>123M</td>
</tr>
<tr>
<td>2,000</td>
<td>42M</td>
<td>1037M</td>
</tr>
</table>
<p><b>Tasklets</b>:</p>
<table border="1">
<th>Num Tasklets</th>
<th>Resident Size</th>
<th>Virtual Size</th>
<tr>
<td>2</td>
<td>3128K</td>
<td>21M</td>
</tr>
<tr>
<td>200</td>
<td>3164K</td>
<td>21M</td>
</tr>
<tr>
<td>2,000</td>
<td>3408K</td>
<td>22M</td>
</tr>
<tr>
<td><b>20,000</b></td>
<td>5920K</td>
<td>24M</td>
</tr>
<tr>
<td><b>100,000</b></td>
<td>17M</td>
<td>34M</td>
</tr>
</table>
<p><i>One note — the Stackless numbers should be low, but not this low (from my understanding, and review from others), anyone have any ideas?</i></p>
<p>There’s the numbers — lots of threads is going to consume lots of ram. With stackless, a given tasklet is only a few kilobytes in average size and therefore the memory footprint is small when you start raising the count. Additionally, note the two counts at the bottom of the tasklets table; you can’t spawn that many threads (depending on your OS and configuration) and even if you could, the memory footprint would be costly.</p>
<p>Now, in the age of cheap-ass-ram, where you can trick out a desktop or server with 16GB sticks, people might argue “so what” — but on machines where memory is constrained, such as smaller notebooks, embedded devices, or game consoles — this is a critical thing to take into consideration. </p>
<p>If you look at the stackless code, there is another big thing to realize; Stackless like other frameworks or systems which use an scheduler built into the interpreter gives you the benefit/task of scheduling when your tasklets/components/etc execute. This gives you more control, but more responsibility. Stackless offers both cooperative and preemptive scheduling, however the preemptive scheduling doesn’t feel right. <a href="http://www.stackless.com/wiki/Scheduling">more on scheduling here</a></p>
<p>So, we’ve determined that stackless tasklets are smaller, right? Pretty simple.</p>
<p>If you’ve read the other things I’ve written on Kamaelia/Twisted/etc, you’ll recognize the concepts within Stackless pretty quickly — a tasklet is a component, a thread of work and tasklets intercommunicate via channels. For example, here’s a little example of two tasklets communicating:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p495code3'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4953"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code" id="p495code3"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> stackless
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> chicken<span style="color: black;">&#40;</span>channel<span style="color: black;">&#41;</span>:
    channel.<span style="color: black;">send</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'cluck'</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> egg<span style="color: black;">&#40;</span>channel<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> channel.<span style="color: black;">receive</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
channel = stackless.<span style="color: black;">channel</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
stackless.<span style="color: black;">tasklet</span><span style="color: black;">&#40;</span>chicken<span style="color: black;">&#41;</span><span style="color: black;">&#40;</span>channel<span style="color: black;">&#41;</span>
stackless.<span style="color: black;">tasklet</span><span style="color: black;">&#40;</span>egg<span style="color: black;">&#41;</span><span style="color: black;">&#40;</span>channel<span style="color: black;">&#41;</span>
stackless.<span style="color: black;">run</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>Pretty easy, and a tiny amount of code. The concept of tasklets/microthreads isn’t a new one — in fact, it’s how Erlang gets it’s groove on — Erlang doesn’t use native OS threads, instead, it uses microthreads scheduled by the Erlang compiler. However, <i>they are not directly comparable</i>. Stackless isn’t running across cores — Erlang does, stackless, due to the GIL, has to obey the same rules as the rest of python-core. For more on “erlang v. stackless”, see <a href="http://www.reddit.com/r/programming/comments/u2ng/ask_reddit_are_taskletschannels_in_stackless">this</a>.</p>
<p>Oh, and you can share normal object via the channel too:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p495code4'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4954"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code" id="p495code4"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> stackless
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> yes<span style="color: black;">&#40;</span>channel<span style="color: black;">&#41;</span>:
    x = channel.<span style="color: black;">receive</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    x.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'yes'</span><span style="color: black;">&#41;</span>
    channel.<span style="color: black;">send</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> no<span style="color: black;">&#40;</span>channel<span style="color: black;">&#41;</span>:
    x = channel.<span style="color: black;">receive</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    x.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'no'</span><span style="color: black;">&#41;</span>
    channel.<span style="color: black;">send</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>
&nbsp;
channel = stackless.<span style="color: black;">channel</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
stackless.<span style="color: black;">tasklet</span><span style="color: black;">&#40;</span>yes<span style="color: black;">&#41;</span><span style="color: black;">&#40;</span>channel<span style="color: black;">&#41;</span>
stackless.<span style="color: black;">tasklet</span><span style="color: black;">&#40;</span>no<span style="color: black;">&#41;</span><span style="color: black;">&#40;</span>channel<span style="color: black;">&#41;</span>
channel.<span style="color: black;">send</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
stackless.<span style="color: black;">run</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> channel.<span style="color: black;">receive</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>Moving on, Stackless offers something else — the ability to pickle tasklets. This means you can pickle up a tasklet and send it over the wire to another machine and then unpickle it and continue running it — channels get pickled too. Locally, this means to can save it to disk, and then resume state easily.</p>
<p>You could use this to generate a tasklet which listened on a port for data on the local machine, and passed the data off the wire to the channel — when you pickled the channel or the tasklets with that channel in scope, and sent it over the wire, they would pick up listening on the same port <b>number</b> on the remote machine. You loose current sessions, yes, but you could also detect active sessions and handle those gracefully.</p>
<p>This is nice for say, a component you wanted to be able to easily send to other machines to help load balancing. In theory, you could auto-detect new servers being added to a cluster, and when that server came up into a “ready” state, send it the daemon it should handle — and the tasklets would pick up where they left off (minus the sessions).</p>
<p>Otherwise, pickling channels and tasklets could be used for a few things — you have to think of them in terms of coroutines (<a href="http://en.wikipedia.org/wiki/Coroutine#Implementations_for_Python">here</a>) — you should be able to suspend processing state and then simply resume where you left off. If you’ve got python brains — picke-able generators. You could put them in a database; but the use of that escapes me at the moment.</p>
<p>Oh — and pickled tasklets and channels can be shared amongst different architectures too, as long as that architecture is running the same version of Stackless, and supports Stackless.</p>
<p>To continue on — if you wanted to add threads into the mix as well — Stackless tasklets can be run within Python threads, however those tasklets are local to that thread, and each thread gets it’s own scheduler. Your main application thread has it’s own scheduler, and so on.</p>
<p>Stackless’ tasklet/channel system is quite nice, however note that I’m not saying Stackless is the only way into this magical world — it’s not, especially with a plethora of coroutine/greenlet/etc packages for python today, and the continued work towards making generators more awesome. I’m just showing what Stackless can/could do.</p>
<p>The primitives within Stackless are nice — frankly, I’d like a light weight green thread implementation in python core on which we could build a nice Actor library, as well as support the lower memory footprint/etc. However, in order to use these primitives within Stackless — you’d find yourself building your own abstraction layer/framework (for example, <a href="http://pypi.python.org/pypi/concurrence">concurrence</a>) to really get a lot of mileage out of it. This is why people run twisted on top of it, CCP Games has the uthread library (which you can see <a href="http://svn.python.org/view/stackless/sandbox/libraries/uthread-ccp/uthread.py?view=markup">here</a>) and so on.</p>
<p>The cost of a deployment of Stackless can not be underestimated though — it’s got some magic assembler code within it, which isn’t the most portable of goods (versus OSes, compiler versions, compilers, etc). Some platforms simply aren’t supported due to this. Not to mention, it’s an entirely new interpreter, which has a cost much higher than that of an extension module.</p>
<p>A few people who I’ve been talking with asked me the simple question — “Why hasn’t any of this been pushed into python-core”. Well, in short — it was never really proposed (by Christian), and the changes within Stackless — the last serious discussion was from 2007 (see <a href="http://mail.python.org/pipermail/python-dev/2007-February/071037.html">this</a>).</p>
<p>With Stackless, it’s difficult — I think there is a perceived complexity about the code and then there is real complexity. I suspect both of these are high in the case of Stackless due to the nature of the problem it is trying to solve; namely bolting a feature like this onto an interpreter <b>not meant for it</b>. I think that due to this, and due to Christian and others moving onto the greener pastures of PyPy — inclusion into core simply won’t happen.</p>
<p><b>Resources:</b></p>
<ul>
<li> <a href="http://www.onlamp.com/pub/a/python/2002/02/14/pythonnews.html">http://www.onlamp.com/pub/a/python/2002/02/14/pythonnews.html</a>
<li> <a href="http://www.python.org/dev/peps/pep-0219/">http://www.python.org/dev/peps/pep-0219/</a>
<li> <a href="http://www.python.org/dev/peps/pep-0255/">http://www.python.org/dev/peps/pep-0255/</a>
<li> <a href="http://muharem.wordpress.com/2007/07/31/erlang-vs-stackless-python-a-first-benchmark/">http://muharem.wordpress.com/2007/07/31/erlang-vs-stackless-python-a-first-benchmark/</a>
<li> <a href="http://www.ibm.com/developerworks/library/l-pythrd.html">http://www.ibm.com/developerworks/library/l-pythrd.html</a>
<li> <a href="http://mail.python.org/pipermail/python-dev/2007-February/071037.html">http://mail.python.org/pipermail/python-dev/2007-February/071037.html</a>
<li> <a href="http://members.verizon.net/olsongt/stackless/why_stackless.html">http://members.verizon.net/olsongt/stackless/why_stackless.html</a>
<li> <a href="http://code.google.com/p/stacklessexamples/wiki/StacklessExamples">http://code.google.com/p/stacklessexamples/wiki/StacklessExamples</a>
<li> <a href="http://islab.org/stackless/">http://islab.org/stackless/</a>
</ul>
<p class="wp-flattr-button"></p>]]></content:encoded>
			<wfw:commentRss>http://jessenoller.com/2009/02/23/stackless-you-got-your-coroutines-in-my-subroutines/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Circuits: event driven components.</title>
		<link>http://jessenoller.com/2009/01/31/circuits-event-driven-components/</link>
		<comments>http://jessenoller.com/2009/01/31/circuits-event-driven-components/#comments</comments>
		<pubDate>Sat, 31 Jan 2009 17:32:38 +0000</pubDate>
		<dc:creator>jesse</dc:creator>
				<category><![CDATA[concurrency]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[pycon 2009]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://jessenoller.com/?p=407</guid>
		<description><![CDATA[Next up in the GBLOSTR (great big list of stuff to review) is the Circuits library by James Mills (here and here)  I'm familiar only with James Mills' posts on python-list, but more recently, I know he's been working on getting some level of multiprocessing into circuits - circuits was already on my ...]]></description>
			<content:encoded><![CDATA[<p>Next up in the GBLOSTR (great big list of stuff to review) is the Circuits library by James Mills (<a href="http://pypi.python.org/pypi/circuits" target="_blank">here</a> and <a href="http://freehg.org/u/prologic/circuits/" target="_blank">here</a>)  I’m familiar only with James Mills’ posts on python-list, but more recently, I know he’s been working on getting some level of multiprocessing into circuits — circuits was already on my research list, but I bumped it up on the queue because we started chatting.</p>
<p>Let me state this: these are slightly cleaned up versions of my notes as I am learning these modules — some of them have higher learning curves for me than others.</p>
<p>Circuits is, well — an event based “framework” (again, note the small f) based around the concept of Components (big C!) consuming/reacting and in turn generating events — all asynchronously.</p>
<p>James’ goals seem pretty simple — build something with no external dependencies, that’s compact (I should say, the core.py is &lt; 500 lines) and that makes it easy to build scalable messaging based (event based) systems. Did he succeed — don’t know! Let’s dig in.</p>
<p><span id="more-407"></span></p>
<p><b>Note</b>:Given his site is/was down at the time of this writing, I simply cloned the hg repo (<a href="http://freehg.org/u/prologic/circuits/" target="_blank">here</a>) and used that for all the code and documentation, which is why I am going to sparse on direct links to the documentation. Also note, that pulling from tip introduces dependencies on python 2.6.</p>
<p>Starting with the quickstart — always a good place to jump to, James outlines the very basics — as in, the very, very basics via a simple code example, which I have paraphrased, renamed the objects of and… you get the picture:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code5'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4075"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code" id="p407code5"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> circuits <span style="color: #ff7700;font-weight:bold;">import</span> listener, Event, Component, Manager
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> AnEvent<span style="color: black;">&#40;</span>Event<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;AnEvent Event&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> TheComponent<span style="color: black;">&#40;</span>Component<span style="color: black;">&#41;</span>:
&nbsp;
    @listener<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;anevent&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> on_anevent<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;">print</span> <span style="color: #483d8b;">&quot;hello, I got an event&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    manager = Manager<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    thecomponent = TheComponent<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    manager += thecomponent
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>:
        manager.<span style="color: black;">push</span><span style="color: black;">&#40;</span>AnEvent<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, <span style="color: #483d8b;">&quot;anevent&quot;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #008000;">True</span>:
        <span style="color: #ff7700;font-weight:bold;">try</span>:
            manager.<span style="color: black;">flush</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">KeyboardInterrupt</span>:
            <span style="color: #ff7700;font-weight:bold;">break</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>And of course, if you run this — you see “hello, I got an event” print 10 times. Simple! But here there be magic, so let’s break it down. First, the events.</p>
<p>Here, we subclass and generate a new event:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code6'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4076"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p407code6"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> AnEvent<span style="color: black;">&#40;</span>Event<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;AnEvent Event&quot;</span></pre></td></tr></table></div>

<p>If you look in core.py, you’ll find that Event is a container — there’s some magic here at first glance — but really all this does (see __new__) is construct a new object of the passed in class, and chain any arguments into attributes. The rest is just accessing and comparison — for example:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code7'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4077"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code" id="p407code7"><pre class="python" style="font-family:monospace;"><span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">from</span> circuits <span style="color: #ff7700;font-weight:bold;">import</span> Event          
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">class</span> x<span style="color: black;">&#40;</span>Event<span style="color: black;">&#41;</span>:
... 	<span style="color: #483d8b;">&quot;an x event&quot;</span>
... 
<span style="color: #66cc66;">&gt;&gt;&gt;</span> y = x<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">2</span>,<span style="color: #ff4500;">3</span>,<span style="color: #ff4500;">4</span>,arg_one=<span style="color: #483d8b;">'foo'</span>,arg_two=<span style="color: #483d8b;">'bar'</span><span style="color: black;">&#41;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">print</span> y
<span style="color: #66cc66;">&lt;</span>x/ <span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span>, <span style="color: #ff4500;">4</span>, arg_two=bar, arg_one=foo<span style="color: black;">&#41;</span><span style="color: #66cc66;">&gt;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span></pre></td></tr></table></div>

<p>This means, that you can pass in any number of positional arguments and keyword arguments, and they’ll be packed into your event. More on this later.</p>
<p>Moving on, the next thing we define is TheComponent:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code8'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4078"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p407code8"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> TheComponent<span style="color: black;">&#40;</span>Component<span style="color: black;">&#41;</span>:
&nbsp;
    @listener<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;anevent&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> on_anevent<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;">print</span> <span style="color: #483d8b;">&quot;hello, I got an event&quot;</span></pre></td></tr></table></div>

<p>The parent class of this object is a little bit more magical. James doesn’t seem shy of the metaprogramming:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code9'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4079"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p407code9"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> Component<span style="color: black;">&#40;</span>BaseComponent<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #0000cd;">__metaclass__</span> = HandlersType</pre></td></tr></table></div>

<p>Nuts. Right above it though is the definition of BaseComponent which is slightly simpler but reveals something interesting — each component can be passed in a channel, and the default is None (more on channels in a bit). Additionally, we see BaseComponent is a subclass of a Manager. Components are managers, and managers are components. </p>
<p>Finkle is einhorn, einhorn is Finkle!</p>
<p>The metaclass does magical object construction stuff and method management/etc. Dragons.</p>
<p>So, the superclass has two addition methods — register() and unregister() which control the component’s registration with the manager (more later). Otherwise, it doesn’t have a lot else, except for the on_anevent() method we’ve added.</p>
<p>And made fancy with a decorator (mandatory pieces of flair)!</p>
<p>This code bit:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code10'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40710"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p407code10"><pre class="python" style="font-family:monospace;">    @listener<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;anevent&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> on_anevent<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;">print</span> <span style="color: #483d8b;">&quot;hello, I got an event&quot;</span></pre></td></tr></table></div>

<p>Essentially means “this method reacts to this event” — so, let’s look at the listener decorator a bit. The decorator is in core.py, and the docstring explains a lot more about the various arguments the decorator can take, but not very clearly. I guess you had to be there.</p>
<p>The one thing you notice though, is that the decorator adds some method attributes to your method — things like f.type, f.target, etc. And then something called f.br, the use of which isn’t clear to me right now. You can however have a single handler listen for multiple events:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code11'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40711"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p407code11"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> TheComponent<span style="color: black;">&#40;</span>Component<span style="color: black;">&#41;</span>:
&nbsp;
    @listener<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;foobar&quot;</span>, <span style="color: #483d8b;">&quot;anevent&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> on_anevent<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;">print</span> <span style="color: #483d8b;">&quot;i listen for foobar and anevent&quot;</span></pre></td></tr></table></div>

<p><b>note</b>: James explained the .br attribute:<br />
<blockquote>
handler.br is used in the BaseComponent’s send(…), and iter(…). It is used to determine which “branch” to follow. The args and kwargs of an Event are intelligently applied to an event handler depending on the signature of the event handler. (It took some time to get right — but basically it means you can’t go wrong!)
</p></blockquote>
<p>In short — we now have a registered listener for an event named “anevent” — when an event is pushed (more on this later). More recently James altered it so that if you define a component, any method which doesn’t start with a _ in the name will explicitly become an event handler of “listener” type and listens on a channel which is based off the method name.</p>
<p>We can refactor the original code like this:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code12'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40712"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p407code12"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> TheComponent<span style="color: black;">&#40;</span>Component<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> anevent<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;">print</span> <span style="color: #483d8b;">&quot;hello, I got an event&quot;</span></pre></td></tr></table></div>

<p>And it works just as well — which is a nice improvement. Here’s the note from James on this:</p>
<blockquote><p>
Basically, the new HandlersType (metclass) means that every method defined in a sub-classes Component that have not been previously defined as event handlers with the @listener decorator or do not start with a _, are automagically turned into event handlers listening on a channel that is the name of the method.</p>
<p>The use of the @listener decorator is still required for:</p>
<ul>
<li>Defining filters
<li>Defining event handlers listening on multiple channels.
<li>Defining event handlers listening on foreign targets.
</ul>
</blockquote>
<p>Next up is the main function — here we instantiate a new Manager object, which if you look at the code of this, you’ll notice right off the bat that there’s a startling number of __ method overloading. Which explains this line:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code13'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40713"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p407code13"><pre class="python" style="font-family:monospace;">    manager += thecomponent</pre></td></tr></table></div>

<p>This is handled by the manager’s __iadd__ method:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code14'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40714"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p407code14"><pre class="python" style="font-family:monospace;">    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__iadd__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, y<span style="color: black;">&#41;</span>:
        y.<span style="color: black;">register</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">manager</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">hasattr</span><span style="color: black;">&#40;</span>y, <span style="color: #483d8b;">&quot;registered&quot;</span><span style="color: black;">&#41;</span>:
            y.<span style="color: black;">registered</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span></pre></td></tr></table></div>

<p>This means that when you append it onto the manager (something more explicit would be nice — brevity and terseness be damned) it calls the register function on the component. Reading through that method is actually quite telling as it introspects the current object (a component) and extracts the callable methods and then pulls out the handlers/channels for a given event and calls .add on the manager. A given component may have multiple listeners for a given event inside of a component:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code15'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40715"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code" id="p407code15"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> TheComponent<span style="color: black;">&#40;</span>Component<span style="color: black;">&#41;</span>:
&nbsp;
    @listener<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;foobar&quot;</span>, <span style="color: #483d8b;">&quot;anevent&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> on_anevent<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;">print</span> <span style="color: #483d8b;">&quot;i listen for foobar and anevent&quot;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> anevent<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;">print</span> <span style="color: #483d8b;">&quot;hello, I got an event&quot;</span></pre></td></tr></table></div>

<p>These handlers are all registered with the manager. Now, something I want to clear up is that when you declare:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code16'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40716"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p407code16"><pre class="python" style="font-family:monospace;">    @listener<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;anevent&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> on_anevent<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;">print</span> <span style="color: #483d8b;">&quot;hello, I got an event&quot;</span></pre></td></tr></table></div>

<p>The “anevent” defines the <b>channel</b> that listener listens on. It’s easy to say “listens for events” — but really what this is is a subscription to a channel. This means you can define a listener with, well — no event:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code17'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40717"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p407code17"><pre class="python" style="font-family:monospace;">    @listener<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #008000;">all</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;">print</span> <span style="color: #483d8b;">&quot;i listen for everything&quot;</span></pre></td></tr></table></div>

<p>It’s like having all the premium channels. </p>
<p>Back to the manager though (the above was a light bulb going off in my head) — next we see that we “push” events into the manager. This is actually pretty simple:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code18'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40718"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code" id="p407code18"><pre class="python" style="font-family:monospace;">    <span style="color: #ff7700;font-weight:bold;">def</span> push<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, event, channel, target=<span style="color: #008000;">None</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;&quot;E.push(event, channel, target=None) -&gt; None
&nbsp;
        Push the given event onto the given channel.
        This will queue the event up to be processed later
        by flushEvents. If target is given, the event will
        be queued for processing by the component given by
        target.
        &quot;&quot;&quot;</span>
&nbsp;
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>.<span style="color: black;">manager</span> == <span style="color: #008000;">self</span>:
            <span style="color: #008000;">self</span>._queue.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>event, channel, target<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">else</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">manager</span>.<span style="color: black;">push</span><span style="color: black;">&#40;</span>event, channel, target<span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>This means we can push events into the manager, and target them at a specific component. The definition of an event in the case of a listener is actually the creation of a <b>channel</b>.</p>
<p>The push method exposes something else — it seems possible to create a manager which is actually a pointer to another manager (a proxy) alas, I don’t see how to do that. Hooray!</p>
<p>So, we can create new events and push them into the manager which pipes them off to the channels who have assigned listeners. Easy! We flush the manager’s queue so all events are pushed to the components, and we’re done.</p>
<p>So what can we use these basics for? Easy — building components which stack on top of each other which contain other components which subscribe to a given event. In the examples directory, James has done an excellent job showcasing a lot of problems which he solves using the core circuits library. In fact, the examples explain a lot more about how things work than the core code itself.</p>
<p>One of the questions I had in working though all of this, is what happens if you define a general event — can the handler gain access to arguments within the event? Does it need to? Is it simply sufficient for a listener on a given channel to know the name/type of an event and react to it?</p>
<p>The answer is, well, yesandno. Let’s say we do this:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code19'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40719"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code" id="p407code19"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> circuits <span style="color: #ff7700;font-weight:bold;">import</span> listener, Event, Component, Manager
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> AnEvent<span style="color: black;">&#40;</span>Event<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;AnEvent Event&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> TheComponent<span style="color: black;">&#40;</span>Component<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> anevent<span style="color: black;">&#40;</span><span style="color: #008000;">self</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;">print</span> args, kwargs
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    manager = Manager<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    thecomponent = TheComponent<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    manager += thecomponent
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>:
        manager.<span style="color: black;">push</span><span style="color: black;">&#40;</span>AnEvent<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">2</span>,<span style="color: #ff4500;">3</span>, no=<span style="color: #483d8b;">'yes'</span>, yes=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>, <span style="color: #483d8b;">&quot;anevent&quot;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #008000;">True</span>:
        <span style="color: #ff7700;font-weight:bold;">try</span>:
            manager.<span style="color: black;">flush</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">KeyboardInterrupt</span>:
            <span style="color: #ff7700;font-weight:bold;">break</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>You would see:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code20'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40720"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p407code20"><pre class="python" style="font-family:monospace;"><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'yes'</span>: <span style="color: #008000;">False</span>, <span style="color: #483d8b;">'no'</span>: <span style="color: #483d8b;">'yes'</span><span style="color: black;">&#125;</span>
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'yes'</span>: <span style="color: #008000;">False</span>, <span style="color: #483d8b;">'no'</span>: <span style="color: #483d8b;">'yes'</span><span style="color: black;">&#125;</span>
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'yes'</span>: <span style="color: #008000;">False</span>, <span style="color: #483d8b;">'no'</span>: <span style="color: #483d8b;">'yes'</span><span style="color: black;">&#125;</span>
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'yes'</span>: <span style="color: #008000;">False</span>, <span style="color: #483d8b;">'no'</span>: <span style="color: #483d8b;">'yes'</span><span style="color: black;">&#125;</span>
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'yes'</span>: <span style="color: #008000;">False</span>, <span style="color: #483d8b;">'no'</span>: <span style="color: #483d8b;">'yes'</span><span style="color: black;">&#125;</span>
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'yes'</span>: <span style="color: #008000;">False</span>, <span style="color: #483d8b;">'no'</span>: <span style="color: #483d8b;">'yes'</span><span style="color: black;">&#125;</span>
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'yes'</span>: <span style="color: #008000;">False</span>, <span style="color: #483d8b;">'no'</span>: <span style="color: #483d8b;">'yes'</span><span style="color: black;">&#125;</span>
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'yes'</span>: <span style="color: #008000;">False</span>, <span style="color: #483d8b;">'no'</span>: <span style="color: #483d8b;">'yes'</span><span style="color: black;">&#125;</span>
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'yes'</span>: <span style="color: #008000;">False</span>, <span style="color: #483d8b;">'no'</span>: <span style="color: #483d8b;">'yes'</span><span style="color: black;">&#125;</span>
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'yes'</span>: <span style="color: #008000;">False</span>, <span style="color: #483d8b;">'no'</span>: <span style="color: #483d8b;">'yes'</span><span style="color: black;">&#125;</span></pre></td></tr></table></div>

<p>Awesome. The arguments the event is created with are passed directly into the listener for that, so as long as you have the right signature on the method, you should be golden.</p>
<p>Which leaves us with a basic question — if messages have to be pushed into the manager on a given channel, how do we build something which is an event generator? In other words — how do we make something which “listens” and then generates the matching events.</p>
<p>To know that — we look in the lib/ directory (which the examples make prodigious use of) and we’ll focus on io.py which listens on stdin:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code21'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40721"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code" id="p407code21"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> circuits <span style="color: #ff7700;font-weight:bold;">import</span> listener, Event, Component, Manager
<span style="color: #ff7700;font-weight:bold;">from</span> circuits.<span style="color: black;">lib</span>.<span style="color: black;">io</span> <span style="color: #ff7700;font-weight:bold;">import</span> Stdin
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> DogBot<span style="color: black;">&#40;</span>Stdin<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> read<span style="color: black;">&#40;</span><span style="color: #008000;">self</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;">print</span> args, kwargs
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    manager = Manager<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    dog = DogBot<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    manager += dog
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #008000;">True</span>:
        <span style="color: #ff7700;font-weight:bold;">try</span>:
            manager.<span style="color: black;">flush</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            dog.<span style="color: black;">poll</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">KeyboardInterrupt</span>:
            <span style="color: #ff7700;font-weight:bold;">break</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>All this does is create a new component which listens for the read event that Stdin generates and then prints off what we see coming in off the command line:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code22'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40722"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p407code22"><pre class="python" style="font-family:monospace;">thumper:circuits jesse$ python2.6 dog.<span style="color: black;">py</span> 
a line <span style="color: #ff7700;font-weight:bold;">is</span> one argument
<span style="color: black;">&#40;</span><span style="color: #483d8b;">'a line is one argument<span style="color: #000099; font-weight: bold;">\n</span>'</span>,<span style="color: black;">&#41;</span> <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span></pre></td></tr></table></div>

<p>That means the read event needs to parse the passed in line and then (re)issue and event for some other listener to manage. Let’s define some addition events:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p407code23'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40723"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code" id="p407code23"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> Sit<span style="color: black;">&#40;</span>Event<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;&quot; Sit event, no args &quot;&quot;&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Say<span style="color: black;">&#40;</span>Event<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;&quot; Speak event
     args: what to say
    &quot;&quot;&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> DogBot<span style="color: black;">&#40;</span>Stdin<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> read<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #66cc66;">*</span>args, <span style="color: #66cc66;">**</span>kwargs<span style="color: black;">&#41;</span>:
        command = args<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>.<span style="color: black;">strip</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'<span style="color: #000099; font-weight: bold;">\n</span>'</span><span style="color: black;">&#41;</span>.<span style="color: black;">split</span><span style="color: black;">&#40;</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> command:
            <span style="color: #ff7700;font-weight:bold;">return</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> command<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span> == <span style="color: #483d8b;">'sit'</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">push</span><span style="color: black;">&#40;</span>Sit<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, <span style="color: #483d8b;">'sit'</span>, <span style="color: #008000;">self</span>.<span style="color: black;">channel</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">elif</span> command<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span> == <span style="color: #483d8b;">'say'</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">push</span><span style="color: black;">&#40;</span>Say<span style="color: black;">&#40;</span><span style="color: #483d8b;">' '</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>command<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span>:<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>, <span style="color: #483d8b;">'say'</span>, <span style="color: #008000;">self</span>.<span style="color: black;">channel</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> sit<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;">print</span> <span style="color: #483d8b;">'i am now sitting'</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> say<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, words<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'&lt;dog&gt;%s&lt;/dog&gt;'</span> <span style="color: #66cc66;">%</span> words</pre></td></tr></table></div>

<p>Rudimentary — but you get the idea. For networking, you’d need to bind the socket and then read off/generate the events — this is largely covered by the sockets.py module in lib, as well as irc, webserver and smtp listeners.</p>
<p>All in all — it’s pretty simple to construct components, it could be made a bit easier with less metaprogramming and more, well, methods but a great deal more documentation could help too. I’m not too fond of too much metaprogramming — I tend to think it makes code rather unapproachable in general.</p>
<p>The (event/channel)/subscription model used here is nice as well — you can easily create your own little asynchronous network daemon or something as simple as what I did above very quickly (once you know what’s going on). It is obviously still evolving — James is putting a lot of work into it. If you’re looking for a compact little library, this would be good to check out.</p>
<p class="wp-flattr-button"></p>]]></content:encoded>
			<wfw:commentRss>http://jessenoller.com/2009/01/31/circuits-event-driven-components/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A gentle overview of Kamaelia or “it’s axon, stupid”</title>
		<link>http://jessenoller.com/2009/01/29/a-gentle-overview-of-kamaelia-or-its-axon-stupid/</link>
		<comments>http://jessenoller.com/2009/01/29/a-gentle-overview-of-kamaelia-or-its-axon-stupid/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 14:29:34 +0000</pubDate>
		<dc:creator>jesse</dc:creator>
				<category><![CDATA[concurrency]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[pycon 2009]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://jessenoller.com/?p=401</guid>
		<description><![CDATA[Note:This is the first post in what I hope will be a series leading up to my concurrency/distributed systems talk at PyCon. I'm steadily working through experimenting with and learning the various frameworks/libraries in the python ecosystem.

I reserve the right (and probably will) to revise these entries based on feedback from people (mainly the ...]]></description>
			<content:encoded><![CDATA[<p><b>Note:</b>This is the first post in what I hope will be a series leading up to my concurrency/distributed systems talk at PyCon. I’m steadily working through experimenting with and learning the various frameworks/libraries in the python ecosystem.</p>
<p>I reserve the right (and probably will) to revise these entries based on feedback from people (mainly the author(s) of said tool(s)). I will also add additional bits and pieces as I learn and explore more. Code and examples will be checked into my pycon 2009 bitbucket site <a href="http://bitbucket.org/jnoller/pycon_2009/src/" target="_blank">here</a><b>/Note</b></p>
<p>For awhile now, I’ve been meaning to dig into <a href="http://www.kamaelia.org" target="_blank">Kamaelia</a> but was largely put off by what I tend to call the “twisted effect”. What this means is that when I go looking for libraries and small components, I go looking for a library — not a “solution”. I also worry about the “once you go in, you must follow this paradigm” effect. I’m not going to say that these feeling continue to be founded, or are completely rational — after all, I am digging into it, yes? It’s the thought that once you adopt the “one true way of doing things” you’re trapped in that solution/framework “forever” — ironically, I love Django for it’s “conceptual integrity” and full-stack approach. No, I don’t understand me either.</p>
<p><span id="more-401"></span></p>
<p>Also, as time has progressed, I have found that part of me yearns for a clean and simple to use “framework” (note the small “f”) that would help build out a large system without introducing a lot of complexity. Ideally, that framework would allow me to swap components in and out — think of web frameworks like django and turbogears — in this case, instead of using stock localized IPC, I might want to swap in a simple messaging protocol (Pyro, XMPP, etc).</p>
<p>It’s also a matter of marketing and approachability — things have improved on both websites mind you. Looking at Kamaelia’s website though, I don’t find it approachable, as it’s not immediately clear <b>what</b> the core idea is, or what the difference between Axon (the core) and Kamaelia (the project) is. For example, if I had one critique, I would say that Axon should become it’s own “project”/library in and of itself, and almost have it’s own website. It would be like ripping Twisted’s reactor out and making it a completely separate library.</p>
<p>Kamaelia, like <a href="http://twistedmatrix.com/trac/" target="_blank">Twisted</a>, is based on a “simple” core — in this case, it’s the Axon library which has some very simple goals and paradigms it seeks to fulfill. To quote the <a href="http://www.kamaelia.org/Docs/Axon/Axon.html" target="_blank">Axon</a> page:</p>
<blockquote><p>
Axon is a component concurrency framework. With it you can create software “components” that can run concurrently with each other. Components have “inboxes” and “outboxes” through with they communicate with other components.</p>
<p>A component may send a message to one of its outboxes. If a linkage has been created from that outbox to another component’s inbox; then that message will arrive in the inbox of the other component. In this way, components can send and receive data — allowing you to create systems by linking many components together.</p>
<p>Each component is a microprocess — rather like a thread of execution. A scheduler takes care of making sure all microprocesses (and therefore all components) get regularly executed. It also looks after putting microprocesses to sleep (when they ask to be) and waking them up (for example, when something arrives in one of their inboxes).
</p></blockquote>
<p>This by itself is the shining gem of the Kamaelia ecosystem — everything else is applications or additional utilities built on this simple core. This is where the website confusion comes in — where does “solutions built with axon (e.g. kamaelia)” end and Axon begin? The core design (of Axon) is very simple though: <i>build a component which communicates via message passing</i>.</p>
<p>Message passing is a relatively simple concept. Component A generates some work, and then sends it to Component (Not A). Messages are handled by the receiver and results can be passed (via a message) to someone else.</p>
<p>Very, very simple. You can add on little factoids about the fact that messages sent and received are handled in asynchronous fashion, messages can be sent locally — or across a wide network, etc — but largely those are component implementation details.</p>
<p>Which gets us back to Axon.</p>
<p>Since I’m interested in the core — and not video transcoders — I hit up the MiniAxon tutorial <a href="http://www.kamaelia.org/MiniAxon" target="_blank">here</a> and worked through it — even then, I don’t really think it did Axon complete justice. I then jumped into the “<a href="http://edit.kamaelia.org/cgi-bin/blog/blog.cgi?rm=viewpost&#038;nodeid=1113495151" target="_blank">How to write new components</a>” article by Michael.</p>
<p>The second tutorial, in my humble opinion, should be the first article users are directed to, while it has some polishing issues, I found it to really explain what the fruit was going on — and what Axon is. </p>
<p>Reading through both of these, you begin to realize that Axon is built on the core concept of Python generators and yielding control to a scheduler. For example:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p401code24'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40124"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code" id="p401code24"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> sender<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
   sock = <span style="color: #dc143c;">socket</span>.<span style="color: #dc143c;">socket</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">socket</span>.<span style="color: black;">AF_INET</span>, <span style="color: #dc143c;">socket</span>.<span style="color: black;">SOCK_DGRAM</span>, <span style="color: #dc143c;">socket</span>.<span style="color: black;">IPPROTO_UDP</span><span style="color: black;">&#41;</span>
   sock.<span style="color: black;">bind</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>ANY,SENDERPORT<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
   sock.<span style="color: black;">setsockopt</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">socket</span>.<span style="color: black;">IPPROTO_IP</span>, <span style="color: #dc143c;">socket</span>.<span style="color: black;">IP_MULTICAST_TTL</span>, <span style="color: #ff4500;">255</span><span style="color: black;">&#41;</span>
   <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #ff4500;">1</span>:
      <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0.5</span><span style="color: black;">&#41;</span>
      sock.<span style="color: black;">sendto</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Hello World&quot;</span>, <span style="color: black;">&#40;</span>MCAST_ADDR,MCAST_PORT<span style="color: black;">&#41;</span> <span style="color: black;">&#41;</span><span style="color: #66cc66;">;</span>
      <span style="color: #ff7700;font-weight:bold;">yield</span> <span style="color: #ff4500;">1</span></pre></td></tr></table></div>

<p>If you’re familiar with python generators, you know that what this function does is send a message to a socket, and then hand control back to the main program. It will do so forever until the controller exits. </p>
<p>This paradigm is key to Axon: components send and receive messages via mailboxes (by far, one of the best descriptions/abstractions I’ve seen for this) — the components do the work sent/generated and then put it in the right outbox, and then yield control, courtesy of Enhanced Generators (see <a href="http://www.python.org/dev/peps/pep-0342/" target="_blank">PEP 342</a>)</p>
<p>Yes, coroutines/greenlets/tasklets — stop bothering me.</p>
<p>In the tutorial I linked above, Michael takes the very simple network script and ports it to Axon. Here’s my simple experiment that drops the networking code and cuts to the mailbox system. In this case, all I want to do is send and receive the lyrics to the meow mix commercial, forever:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p401code25'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40125"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
</pre></td><td class="code" id="p401code25"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> Axon
&nbsp;
LYRICS=<span style="color: #483d8b;">&quot;I want chicken I want liver Meow Mix Meow Mix Please Deliver.&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Producer<span style="color: black;">&#40;</span>Axon.<span style="color: black;">Component</span>.<span style="color: black;">component</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> main<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;">while</span> <span style="color: #ff4500;">1</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">send</span><span style="color: black;">&#40;</span>LYRICS, <span style="color: #483d8b;">&quot;outbox&quot;</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">yield</span> <span style="color: #ff4500;">1</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Sender<span style="color: black;">&#40;</span>Axon.<span style="color: black;">Component</span>.<span style="color: black;">component</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>.__super.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> main<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;">while</span> <span style="color: #ff4500;">1</span>:
            <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>.<span style="color: black;">dataReady</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;inbox&quot;</span><span style="color: black;">&#41;</span>:
                message = <span style="color: #008000;">self</span>.<span style="color: black;">recv</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
                <span style="color: #008000;">self</span>.<span style="color: black;">send</span><span style="color: black;">&#40;</span>message, <span style="color: #483d8b;">&quot;outbox&quot;</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">yield</span> <span style="color: #ff4500;">1</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Receiver<span style="color: black;">&#40;</span>Axon.<span style="color: black;">Component</span>.<span style="color: black;">component</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>.__super.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> main<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;">while</span> <span style="color: #ff4500;">1</span>:
            message = <span style="color: #008000;">self</span>.<span style="color: black;">recv</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">print</span> message
            <span style="color: #ff7700;font-weight:bold;">yield</span> <span style="color: #ff4500;">1</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> tests<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>: 
    <span style="color: #ff7700;font-weight:bold;">from</span> Axon.<span style="color: black;">Scheduler</span> <span style="color: #ff7700;font-weight:bold;">import</span> scheduler 
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">class</span> testComponent<span style="color: black;">&#40;</span>Axon.<span style="color: black;">Component</span>.<span style="color: black;">component</span><span style="color: black;">&#41;</span>: 
        <span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>: 
            producer= Producer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            sender = Sender<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            receiver = Receiver<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> 
&nbsp;
            <span style="color: #008000;">self</span>.<span style="color: black;">link</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>producer, <span style="color: #483d8b;">&quot;outbox&quot;</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#40;</span>sender, <span style="color: #483d8b;">&quot;inbox&quot;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">link</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>sender, <span style="color: #483d8b;">&quot;outbox&quot;</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#40;</span>receiver, <span style="color: #483d8b;">&quot;inbox&quot;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">addChildren</span><span style="color: black;">&#40;</span>producer, sender, receiver<span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">yield</span> Axon.<span style="color: black;">Ipc</span>.<span style="color: black;">newComponent</span><span style="color: black;">&#40;</span><span style="color: #66cc66;">*</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">children</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> 
            <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #ff4500;">1</span>: 
                <span style="color: #008000;">self</span>.<span style="color: black;">pause</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> 
                <span style="color: #ff7700;font-weight:bold;">yield</span> <span style="color: #ff4500;">1</span>
&nbsp;
    harness = testComponent<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> 
    harness.<span style="color: black;">activate</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> 
    scheduler.<span style="color: black;">run</span>.<span style="color: black;">runThreads</span><span style="color: black;">&#40;</span>slowmo=<span style="color: #ff4500;">0.1</span><span style="color: black;">&#41;</span> 
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__==<span style="color: #483d8b;">&quot;__main__&quot;</span>: 
    tests<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>Now, this uses knowledge from both tutorials, and the <a href="http://www.kamaelia.org/Docs/Axon/Axon.Component.html" target="_blank">Axon.Component</a> documentation. The component documentation can be hard to find, and not so easy to navigate too.</p>
<p>If we break one of the classes/components down and look at the “magic” provided by the component subclass, it gets clearer — in this case, I’ve “added” back in the methods from the component superclass, minus the doc strings:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p401code26'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40126"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
</pre></td><td class="code" id="p401code26"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> Sender<span style="color: black;">&#40;</span>Axon.<span style="color: black;">Component</span>.<span style="color: black;">component</span><span style="color: black;">&#41;</span>:
    <span style="color: #808080; font-style: italic;"># First, subclass the Axon Component class, this provides us with the</span>
    <span style="color: #808080; font-style: italic;"># basic inbox/outbox static members that look like this:</span>
    Inboxes = <span style="color: black;">&#123;</span> <span style="color: #483d8b;">&quot;inbox&quot;</span>   : <span style="color: #483d8b;">&quot;Send the FOO objects to here&quot;</span>,
                <span style="color: #483d8b;">&quot;control&quot;</span> : <span style="color: #483d8b;">&quot;NOT USED&quot;</span>,
              <span style="color: black;">&#125;</span>
    Outboxes = <span style="color: black;">&#123;</span> <span style="color: #483d8b;">&quot;outbox&quot;</span> : <span style="color: #483d8b;">&quot;Emits BAA objects from here&quot;</span>,
                 <span style="color: #483d8b;">&quot;signal&quot;</span> : <span style="color: #483d8b;">&quot;NOT USED&quot;</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>:
        <span style="color: #008000;">self</span>.__super.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
   <span style="color: #ff7700;font-weight:bold;">def</span> recv<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, boxname=<span style="color: #483d8b;">&quot;inbox&quot;</span><span style="color: black;">&#41;</span>:
      <span style="color: #808080; font-style: italic;"># returns the first piece of data in the requested inbox.</span>
&nbsp;
      <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">inboxes</span><span style="color: black;">&#91;</span>boxname<span style="color: black;">&#93;</span>.<span style="color: black;">pop</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
&nbsp;
   <span style="color: #ff7700;font-weight:bold;">def</span> send<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, message, boxname=<span style="color: #483d8b;">&quot;outbox&quot;</span><span style="color: black;">&#41;</span>:
      <span style="color: #808080; font-style: italic;"># appends message to the requested outbox.</span>
&nbsp;
      <span style="color: #008000;">self</span>.<span style="color: black;">outboxes</span><span style="color: black;">&#91;</span>boxname<span style="color: black;">&#93;</span>.<span style="color: black;">append</span><span style="color: black;">&#40;</span>message<span style="color: black;">&#41;</span>
&nbsp;
   <span style="color: #ff7700;font-weight:bold;">def</span> dataReady<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>,boxname=<span style="color: #483d8b;">&quot;inbox&quot;</span><span style="color: black;">&#41;</span>:
      <span style="color: #808080; font-style: italic;"># Returns true if data is available in the requested inbox.</span>
&nbsp;
      <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">inboxes</span><span style="color: black;">&#91;</span>boxname<span style="color: black;">&#93;</span>.<span style="color: black;">local_len</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> main<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;">while</span> <span style="color: #ff4500;">1</span>:
            <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>.<span style="color: black;">dataReady</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;inbox&quot;</span><span style="color: black;">&#41;</span>:
                message = <span style="color: #008000;">self</span>.<span style="color: black;">recv</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
                <span style="color: #008000;">self</span>.<span style="color: black;">send</span><span style="color: black;">&#40;</span>message, <span style="color: #483d8b;">&quot;outbox&quot;</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">yield</span> <span style="color: #ff4500;">1</span></pre></td></tr></table></div>

<p>I think this makes it abundantly clear what’s happening with the method calls on this class. Now, there’s the additional magic of the new tests method — in which we defined a new component, which was actually a component containing and linking the pipelines (connections between mailboxes) between the other components.</p>
<p>Now, the <a href="http://www.kamaelia.org/Docs/Axon/Axon.Ipc.html" target="_blank">Axon.Ipc.*</a> docs aren’t the most helpful — in our case, we called:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p401code27'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40127"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p401code27"><pre class="python" style="font-family:monospace;">    <span style="color: #008000;">self</span>.<span style="color: black;">link</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>producer, <span style="color: #483d8b;">&quot;outbox&quot;</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#40;</span>sender, <span style="color: #483d8b;">&quot;inbox&quot;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    <span style="color: #008000;">self</span>.<span style="color: black;">link</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>sender, <span style="color: #483d8b;">&quot;outbox&quot;</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#40;</span>receiver, <span style="color: #483d8b;">&quot;inbox&quot;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    <span style="color: #008000;">self</span>.<span style="color: black;">addChildren</span><span style="color: black;">&#40;</span>producer, sender, receiver<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">yield</span> Axon.<span style="color: black;">Ipc</span>.<span style="color: black;">newComponent</span><span style="color: black;">&#40;</span><span style="color: #66cc66;">*</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">children</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>Within the main method of a component. We need to look at the link method on the superclass:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p401code28'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40128"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code" id="p401code28"><pre class="python" style="font-family:monospace;">   <span style="color: #ff7700;font-weight:bold;">def</span> link<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, source,sink,<span style="color: #66cc66;">*</span>optionalargs, <span style="color: #66cc66;">**</span>kwoptionalargs<span style="color: black;">&#41;</span>:
      <span style="color: #483d8b;">&quot;&quot;&quot;<span style="color: #000099; font-weight: bold;">\</span>
      Creates a linkage from one inbox/outbox to another.
&nbsp;
      -- source  - a tuple (component, boxname) of where the link should start  
                   from
      -- sink    - a tuple (component, boxname) of where the link should go to
&nbsp;
      Other optional arguments:
&nbsp;
      - passthrough=0  - (the default) link goes from an outbox to an inbox
      - passthrough=1  - the link goes from an inbox to another inbox
      - passthrough=2  - the link goes from an outbox to another outbox
&nbsp;
      See Axon.Postoffice.postoffice.link() for more information.
      &quot;&quot;&quot;</span>
      <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">postoffice</span>.<span style="color: black;">link</span><span style="color: black;">&#40;</span>source, sink, <span style="color: #66cc66;">*</span>optionalargs, \
                                  <span style="color: #66cc66;">**</span>kwoptionalargs<span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>This leads us to the <a href="http://www.kamaelia.org/Docs/Axon/Axon.Postoffice.html" target="_blank">Postoffice</a> class which actually constructs and tracks the links between the components. Here there be dragons.</p>
<p>So, addChildren just registers all of the passed in component instances as children of the newly constructed components (components, all the way down), and then we yield ourself — if you added a ‘print harness’ you’d see:</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p401code29'); return false;">View Code</a> PYTHON</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p40129"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p401code29"><pre class="python" style="font-family:monospace;">Component <span style="color: #dc143c;">__main__</span>.<span style="color: black;">testComponent_5</span> <span style="color: black;">&#91;</span> inboxes : <span style="color: black;">&#123;</span><span style="color: #483d8b;">'control'</span>: <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>, <span style="color: #483d8b;">'inbox'</span>: <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span><span style="color: black;">&#125;</span>
outboxes : <span style="color: black;">&#123;</span><span style="color: #483d8b;">'outbox'</span>: <span style="color: #66cc66;">&lt;&gt;</span>, <span style="color: #483d8b;">'signal'</span>: <span style="color: #66cc66;">&lt;&gt;</span><span style="color: black;">&#125;</span></pre></td></tr></table></div>

<p>This means we’re getting a component back, and then calling .activate on it — .activate is actually a method on the Axon.Microprocess.microprocess class. In our case, it (it being activate) is simply registering our test component (which contains all of the children) with the default scheduler.</p>
<p>At which point, we call scheduler.run.runThreads <b>jazz hands</b>.</p>
<p>I dived into some of the internals here, I ended up having to supplement the documentation with pouring through the code — but I personally think it helps clear things up to remove some of the magic and show what is actually occurring. Most of the time, it seems you simply <b>won’t care</b> — and instead you’d just make and register your happy component and be on your way.</p>
<p>To somewhat summarize what we’re lookin at — a component that subclasses the default Axon.Component uses generators to yield control back and forth, passing messages/work to and from each other via the very clever mailbox/postoffice metaphor.</p>
<p>Now, the interesting thing, once you start digging through things is that your component isn’t a really a Thread — if you wanted to make sure each component was in its own thread, you might instead subclass <a href="http://www.kamaelia.org/Docs/Axon/Axon.ThreadedComponent.html" target="_blank">Axon.ThreadedComponent</a>.</p>
<p>Subclassing this new class looks mighty close to what we did before but instead Uses threads and queues for the message passing. Instead of yield, you just run, and the recv/send methods are backed by queues. Ahh, delicious non judgmental queues.</p>
<p>In any case, Kamaelia — via Axon, is a very nice abstraction on top of a very simple concept — message passing for concurrency. The fact that you can quickly build up a series of components which pass work back and forth via some sort of communications system and not have to worry about the underlying nuances/organization is quite nice.</p>
<p>One of the things Michael Sparks and I have talked about is adding some level of multiprocessing support for Kamaelia — this would actually be insanely easy if I used Axon.ThreadedComponent as the template, but instead used multiprocessing.Queue and multiprocessing.Process as the back end.</p>
<p>Kamaelia itself, is really a series of example components/applications which build on a core (Axon), but you do not need Kamaelia to use Axon effectively. In fact, just on a whim, I decided to whip up a dirty http load tool in Kamaelia. You can see it <a href="http://bitbucket.org/jnoller/pycon_2009/src/tip/kamaelia/http_pain.py" target="_blank">here</a>.</p>
<p>It’s really a hack job — all I did was build off the meowmix demo, swapped in the threaded component and hacked it around a bit. One thing I’d like to know is how to pass in a dynamic number of clients so that I could create the outboxes dynamically in the producer — there wasn’t anything clear in the docs to allow me to do this. Also, it doesn’t shut down.</p>
<p>I’m going to keep hacking around with Axon, it’s pretty neat. Interesting things I’d like to poke around in:</p>
<ul>
<li> Replace the underlying IPC mechanism with multiprocessing.Pipe/Pyro/<a href="http://semanchuk.com/philip/posix_ipc/" target="_blank">posix_ipc</a>
<li> hack on the mp version of the component backend
<li> get a multi-system script running and communicating workloads across the LAN
</ul>
<p class="wp-flattr-button"></p>]]></content:encoded>
			<wfw:commentRss>http://jessenoller.com/2009/01/29/a-gentle-overview-of-kamaelia-or-its-axon-stupid/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Actors, concurrency and Kamaelia</title>
		<link>http://jessenoller.com/2008/10/29/actors-concurrency-and-kamaelia/</link>
		<comments>http://jessenoller.com/2008/10/29/actors-concurrency-and-kamaelia/#comments</comments>
		<pubDate>Wed, 29 Oct 2008 14:57:53 +0000</pubDate>
		<dc:creator>jesse</dc:creator>
				<category><![CDATA[concurrency]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://jessenoller.com/?p=356</guid>
		<description><![CDATA[Recently, I made an offhand comment here about:
I've actually started thinking about/sketching an actor model build on top of MP, using concepts from actors/monitors and things in the ecosystem today
The ensuing comments and discussion were pretty good - but last night Michael Sparks (of Kamaelia) posted a darned nice comment:
Are you aware that a ...]]></description>
			<content:encoded><![CDATA[<p>Recently, I made an offhand comment <a href="http://jessenoller.com/2008/10/27/guido-answers-your-questions/" target="_blank">here</a> about:</p>
<blockquote><p>I’ve actually started thinking about/sketching an actor model build on top of MP, using concepts from actors/monitors and things in the ecosystem today</p></blockquote>
<p>The ensuing comments and discussion were pretty good — but last night Michael Sparks (of Kamaelia) posted a darned nice comment:</p>
<blockquote><p>Are you aware that a complete mini-axon using generators is tiny and the rest is optimisations and extra stuff that you find useful in real world systems? By tiny, I mean this small:<br />   * <a href="http://www.kamaelia.org/MiniAxonFull">http://www.kamaelia.org/MiniAxonFull</a></p>
<p>A mini-axon using processes would be equally lightweight (shorter probably) and pretty awesome.</p>
<p>Also, it’s easy to confuse the two halves of Kamaelia. If you think of Kamaelia as just an actor-type  implementation, then it’s actually more an actor-like implementation, with STM &amp; an internal SOA system of just over 2000 lines (which is how big Axon actually is, excluding comments &amp; docs), with 80,000 lines of examples…</p>
<p>However, personally I view it as a mechanism for building components which happen to be best used in a concurrent fashion. ie rather than viewing it as “a mechanism for using concurrency”, I view it as “OK, assume we have concurrency, how can we use this to assist in building and maintaining systems”. Axon also gives you the tools for taking these concurrent systems, and interfacing between concurrent systems and standard code. (<a href="http://www.kamaelia.org/AxonHandle">http://www.kamaelia.org/AxonHandle</a>) </p>
<p>As a result, I view Axon as a library which provides you with the tools wrapping up idioms useful for building collections of components which be a framework.</p>
<p>Anyway, potato/potato, tomato/tomato — if you like, you like, if you don’t, you don’t.</p>
<p>I’d love to replace our existing process based stuff btw with a multiprocessing based version though. If I was going to go down this route, I’d follow our mini axon tutorial to do so, largely becauseit’s essentially the starting point I took with the multiprocess stuff recently and it worked out pretty well.</p>
<p>Beyond this basic stuff though, I’ve noted that people generally start talking about co-ordination languages and building up pattern repositories. The interesting intersection between these two which you get if you call things components rather than actors is it becomes natural to create components called a chassis. These chassis often instantiate directly in concrete usable form concepts that you’d normally refer to as a pattern — Pipeline, Graphline, Carousel, Backplane, Seq, TPipe, etc.</p>
<p>On a random note, you may want to check out MASCOT “Modular Approach to Software Construction, Operation and Test”. I heard about it late last year, and it appears to have the same sort of architecture as Kamaelia. Interestingly (to me) it makes the same key decision — when you send a message outside your component, you don’t know who is going to receive it. This then enables (and requires) a higher level system for connecting components together. The upshot is highly reusable components. This doesn’t entirely surprise me — my ethos came from recognising that asynchronous hardware systems &amp; network systems look strikingly similar… (cf <a href="http://www.slideshare.net/kamaelian/sociable-software">http://www.slideshare.net/kamaelian/sociable-so…</a>)</p>
<p>Anyway, reference for MASCOT: <a href="http://async.org.uk/Hugo.Simpson/">http://async.org.uk/Hugo.Simpson/</a> — skip down to the end of the page for this PDF: <a href="http://async.org.uk/Hugo.Simpson/MASCOT-3.1-Manual-June-1987.pdf">http://async.org.uk/Hugo.Simpson/MASCOT-3.1-Man…</a> I was really pleased to be pointed at MASCOT, largely because it showed a large number of other domains where the same basic model has been used for well over 30 years… Just with non-existent exposure, and slightly different metaphors. Though we, like it, also have mechanisms for automatically visualising systems, with a 1:1 correspondence. Beyond that this also gives us a model that matches Edward Lee’s “The Problem with threads” — we’d released running code long before that paper was published :-)</p>
<p>Anyway, I’m glad that you’re looking at what we’ve done. If you use it, that’d be great, and I’ll happily merge anything you’d like to have a life. (the only comment I’d make there is metaphors and accessibility count — this is surely the point of python? :-) If you don’t take what we use etc but it helps you solidify your thoughts to “No, I don’t want that, I want this”, then likewise, I’m equally glad. If you do that, I’d love to know what you do try, since I like to merge best practice concurrency ideas into Axon :-)</p>
<p>I’d *REALLY* suggest looking at MASCOT though. Really made my Christmas last year when I was pointed at it.</p>
<p>We’re currently having lots of fun using concurrency, primarily by allowing it to make our lives easier, and forgettable about :) It’d be nice to see something similar on top of multiprocessing (which we’ll do if you don’t, but it’d be great if you did — but I’d understand if your view was that you prefer a pure actor (sender knows receiver) model.</p></blockquote>
<p><cite>Originally posted as a <a href="http://jessenoller.com/2008/10/27/guido-answers-your-questions/#comment-3352784">comment</a> by <a href="http://disqus.com/people/aa2d0ea46169b401151a00b8b97de928/">Michael Sparks</a> on <a href="http://www.jessenoller.com">jessenoller.com comments</a> using <a href="http://disqus.com">Disqus</a>.</cite></p>
<p>I wanted to pull that comment out and showcase what Michael has to say, and in some way, respond. First, yes — I am looking at Kamaelia (from here on out, I’m going to call it “Kam” — I keep transposing the ae). I actually ran through the mini-axon tutorial, and when I have time, I’m trying to tease apart the internals to better understand it.</p>
<p>Fundamentally, I agree with you (Michael) about the aspects of making concurrency easier (and safer). Right now, I think Kam is a pretty darned good start — for a framework *grin*.</p>
<p>When I made the comment I made, I didn’t think it would get the response it got. There has been a dog-pile of discussions about concurrency best practices/etc and in fact, there’s a discussion still going on on the python-list about concurrency stuff going on <a href="http://mail.python.org/pipermail/python-list/2008-October/512902.html" target="_blank">right now</a>.</p>
<p>Personally, I only work on the concurrency stuff part-part time — this includes my minor work on Python-Core. My day job is a test engineer — while I am building highly concurrent (and distributed) tests and I use multiprocessing and threading daily, it’s not my full time pursuit. I am passionate about it, and I am passionate about improving python as a language, and library — and if I can do it as a day job and open source it, or get company time to do it, by golly I will.</p>
<p>When I said “I want to build an actor model” — I was not necessarily talking about doing an implementation for python-core. I’m a big believer in learning-through-implementation — so when I said “build x”, not only did I mean “build something for the world” — I also meant “build something for my own benefit” so I can deep-dive into the concepts, problems etc.</p>
<p>This is why I am adverse to jumping in and simply “using” a framework — not because I don’t think it does something exceedingly well — trust me, I am an opportunistic developer — if I can find a library that does what I need *right now* — I’ll use it.</p>
<p>That being said — I am exploring Kamaelia, and yes hopefully I can steal some time to actually do an implementation of the process-based stuff with multiprocessing. I want to explore everything in the ecosystem today — my discussions with Adam Olsen around this stuff (and around <a href="http://code.google.com/p/python-safethread/" target="_blank">python-safethread</a>) and others has made me really want to explore solutions that help everyone, and take the best ideas and concepts and rolls it into something worthy of Python core.</p>
<p>As I have said before — I believe there is room within Python as a language, and CPython as an implementation of that language — for a virtual buffet of helpful <b>libraries</b> for concurrency and distributed systems. Right now, we have threading, async* and multiprocessing. There is plenty of room to grow. Maybe one day I can steal time to grab more of the concepts from java.util.concurrent and propose them via a PEP. Heck — maybe we can work as a group to propose an actor/monitor implementation for Python-Core.</p>
<p>So — personally, and by way of responding to Michael in a more concrete way: I’m, <b>personally</b> looking at anything I can to learn more about implementations and strategies. If something were to come out of it, and I felt strongly enough to propose inclusion in core, I would write and post a PEP — and not run in blindly.</p>
<p>I’ve <a href="http://code.google.com/p/testbutler/" target="_blank">got</a> <a href="http://code.google.com/p/python-multiprocessing/" target="_blank">more</a> than <a href="http://code.google.com/p/nose-testconfig/" target="_blank">enough</a> stuff to <a href="http://code.google.com/p/pyjavaproperties/" target="_blank">work on</a> in addition to the day job and being a Dad, and yard work. Oh and the day job, which doesn’t involve nearly as much distributed-and-concurrent systems in Python as I’d like :).</p>
<p>Heck — thinking about it we’d need a good messaging implementation too. I’ll put that on the pile too.</p>
<p>Quick Rant (slightly off topic):</p>
<p>Also, can we stop talking about the damned GIL? Yes, you need locks, No, you probably don’t care about the GIL. Stop yammering about how “broken” CPython is because of it– CPython is an implementation, not the final one and not the only one. If the GIL really gets you excited, either drop to a C module, use multiprocessing or something else. The GIL is here to stay for some time — either propose a PEP (and a Patch) that doesn’t break CPython or hush. Enough bike-shedding — discussion is great, especially when something comes out of it, but constantly berating/lamenting things is just a bike shed. The shed is purple, now move on. Purple!</p>
<p>Required Reading ( in addition to Michael’s links):</p>
<ul>
<li><a href="http://www.kamaelia.org/Home" target="_blank">Kamaelia</a>
<li><a href="http://code.google.com/p/python-safethread/" target="_blank">python-safethread</a>
<li><a href="http://twistedmatrix.com/trac/" target="_blank">Twisted</a>
<li><a href="http://dramatis.mischance.net/" target="_blank">Dramatis</a>
<li><a href="http://osl.cs.uiuc.edu/parley/" target="_blank">Parley</a>
<li><a href="http://www.valuedlessons.com/2008/06/message-passing-conccurrency-actor.html" target="_blank">Message Passing Conccurrency (Actor Model) in Python</a>
<li><a href="http://www.ajaxonomy.com/2008/news/toward-better-concurrency" target="_blank">Toward Better Concurrency</a>
<li><a href="http://www.ddj.com/hpc-high-performance-computing/200001985" target="_blank">The Pillars of Concurrency</a>
</ul>
<p class="wp-flattr-button"></p>]]></content:encoded>
			<wfw:commentRss>http://jessenoller.com/2008/10/29/actors-concurrency-and-kamaelia/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Object Caching 1485/1569 objects using disk: basic

Served from: jessenoller.com @ 2012-02-03 23:56:28 -->
