<?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>Terry Jones &#187; python</title>
	<atom:link href="http://blogs.fluidinfo.com/terry/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.fluidinfo.com/terry</link>
	<description>Random thoughts on tech, books, programming, etc.</description>
	<lastBuildDate>Sat, 21 Jan 2012 06:18:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Python code for retrieving all your tweets</title>
		<link>http://blogs.fluidinfo.com/terry/2009/06/24/python-code-for-retrieving-all-your-tweets/</link>
		<comments>http://blogs.fluidinfo.com/terry/2009/06/24/python-code-for-retrieving-all-your-tweets/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 20:44:06 +0000</pubDate>
		<dc:creator>terry</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://blogs.fluidinfo.com/terry/?p=608</guid>
		<description><![CDATA[Here&#8217;s a little Python code to pull back all a user&#8217;s Twitter tweets. Make sure you read the notes at bottom in case you want to use it. import sys, twitter, operator from dateutil.parser import parse twitterURL = &#8216;http://twitter.com&#8217; def fetch&#40;user&#41;: &#160; &#160; data = &#123;&#125; &#160; &#160; api = twitter.Api&#40;&#41; &#160; &#160; max_id = [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a little Python code to pull back all a user&#8217;s Twitter tweets. Make sure you read the notes at bottom in case you want to use it.</p>
<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">import</span> <span class="kw3">sys</span>, twitter, <span class="kw3">operator</span><br />
<span class="kw1">from</span> dateutil.<span class="kw3">parser</span> <span class="kw1">import</span> parse</p>
<p>twitterURL = <span class="st0">&#8216;http://twitter.com&#8217;</span></p>
<p><span class="kw1">def</span> fetch<span class="br0">&#40;</span><span class="kw3">user</span><span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; data = <span class="br0">&#123;</span><span class="br0">&#125;</span><br />
&nbsp; &nbsp; api = twitter.<span class="me1">Api</span><span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; max_id = <span class="kw2">None</span><br />
&nbsp; &nbsp; total = <span class="nu0">0</span><br />
&nbsp; &nbsp; <span class="kw1">while</span> <span class="kw2">True</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; statuses = api.<span class="me1">GetUserTimeline</span><span class="br0">&#40;</span><span class="kw3">user</span>, count=<span class="nu0">200</span>, max_id=max_id<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; newCount = ignCount = <span class="nu0">0</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">for</span> s <span class="kw1">in</span> statuses:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">if</span> s.<span class="kw2">id</span> <span class="kw1">in</span> data:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ignCount += <span class="nu0">1</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">else</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data<span class="br0">&#91;</span>s.<span class="kw2">id</span><span class="br0">&#93;</span> = s<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newCount += <span class="nu0">1</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; total += newCount<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">print</span> &gt;&gt;sys.<span class="me1">stderr</span>, <span class="st0">&quot;Fetched %d/%d/%d new/old/total.&quot;</span> % <span class="br0">&#40;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newCount, ignCount, total<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">if</span> newCount == <span class="nu0">0</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">break</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; max_id = <span class="kw2">min</span><span class="br0">&#40;</span><span class="br0">&#91;</span>s.<span class="kw2">id</span> <span class="kw1">for</span> s <span class="kw1">in</span> statuses<span class="br0">&#93;</span><span class="br0">&#41;</span> &#8211; <span class="nu0">1</span><br />
&nbsp; &nbsp; <span class="kw1">return</span> data.<span class="me1">values</span><span class="br0">&#40;</span><span class="br0">&#41;</span></p>
<p><span class="kw1">def</span> htmlPrint<span class="br0">&#40;</span><span class="kw3">user</span>, tweets<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; <span class="kw1">for</span> t <span class="kw1">in</span> tweets:<br />
&nbsp; &nbsp; &nbsp; &nbsp; t.<span class="me1">pdate</span> = parse<span class="br0">&#40;</span>t.<span class="me1">created_at</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; key = <span class="kw3">operator</span>.<span class="me1">attrgetter</span><span class="br0">&#40;</span><span class="st0">&#8216;pdate&#8217;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; tweets = <span class="kw2">sorted</span><span class="br0">&#40;</span>tweets, key=key<span class="br0">&#41;</span><br />
&nbsp; &nbsp; f = <span class="kw2">open</span><span class="br0">&#40;</span><span class="st0">&#8216;%s.html&#8217;</span> % <span class="kw3">user</span>, <span class="st0">&#8216;wb&#8217;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="kw1">print</span> &gt;&gt;f, <span class="st0">&quot;&quot;</span><span class="st0">&quot;&lt;html&gt;&lt;title&gt;Tweets for %s&lt;/title&gt;<br />
&nbsp; &nbsp; &lt;meta http-equiv=&quot;</span>Content-Type<span class="st0">&quot; content=&quot;</span>text/html;charset=utf<span class="nu0">-8</span><span class="st0">&quot;&gt;<br />
&nbsp; &nbsp; &lt;body&gt;&lt;small&gt;&quot;</span><span class="st0">&quot;&quot;</span> % <span class="kw3">user</span><br />
&nbsp; &nbsp; <span class="kw1">for</span> i, t <span class="kw1">in</span> <span class="kw2">enumerate</span><span class="br0">&#40;</span>tweets<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">print</span> &gt;&gt;f, <span class="st0">&#8216;%d. %s &lt;a href=&quot;%s/%s/status/%d&quot;&gt;%s&lt;/a&gt;&lt;br/&gt;&#8217;</span> % <span class="br0">&#40;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i, t.<span class="me1">pdate</span>.<span class="me1">strftime</span><span class="br0">&#40;</span><span class="st0">&#8216;%Y-%m-%d %H:%M&#8217;</span><span class="br0">&#41;</span>, twitterURL,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw3">user</span>, t.<span class="kw2">id</span>, t.<span class="me1">text</span>.<span class="me1">encode</span><span class="br0">&#40;</span><span class="st0">&#8216;utf8&#8242;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="kw1">print</span> &gt;&gt;f, <span class="st0">&#8216;&lt;/small&gt;&lt;/body&gt;&lt;/html&gt;&#8217;</span><br />
&nbsp; &nbsp; f.<span class="me1">close</span><span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; <br />
<span class="kw1">if</span> __name__ == <span class="st0">&#8216;__main__&#8217;</span>:<br />
&nbsp; &nbsp; <span class="kw3">user</span> = <span class="st0">&#8216;terrycojones&#8217;</span> <span class="kw1">if</span> <span class="kw2">len</span><span class="br0">&#40;</span><span class="kw3">sys</span>.<span class="me1">argv</span><span class="br0">&#41;</span> &lt; <span class="nu0">2</span> <span class="kw1">else</span> <span class="kw3">sys</span>.<span class="me1">argv</span><span class="br0">&#91;</span><span class="nu0">1</span><span class="br0">&#93;</span><br />
&nbsp; &nbsp; data = fetch<span class="br0">&#40;</span><span class="kw3">user</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; htmlPrint<span class="br0">&#40;</span><span class="kw3">user</span>, data<span class="br0">&#41;</span><br />
&nbsp;</div>
<p><strong>Notes:</strong></p>
<p>Fetch all of a user&#8217;s tweets and write them to a file <tt>username.html</tt> (where username is given on the command line).</p>
<p>Output is to a file instead of to stdout as tweet texts are unicode and <tt>sys.stdout.encoding</tt> is <tt>ascii</tt> on my machine, which prevents printing non-ASCII chars.</p>
<p>This code uses the Python-Twitter library. You need to get (via SVN) <a href="http://python-twitter.googlecode.com/svn/trunk">the very latest version</a>, and then you need to fix a tiny bug, <a href="http://groups.google.com/group/python-twitter/msg/6ba85d52d36be02e">described here</a>.  Or wait a while and the SVN trunk will be patched.</p>
<p>This worked flawlessly for <a href="http://jon.es/twitter/terrycojones.html">my 2,300 tweets</a>, but only retrieved about half the tweets of someone who had over 7,000. I&#8217;m not sure what happened there.</p>
<p>There are tons of things that could be done to make the output more attractive and useful. And yes, for nitpickers, the code has a couple of slight inefficiencies :-)</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.fluidinfo.com/terry/2009/06/24/python-code-for-retrieving-all-your-tweets/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>A mixin class allowing Python __init__ methods to work with Twisted deferreds</title>
		<link>http://blogs.fluidinfo.com/terry/2009/05/11/a-mixin-class-allowing-python-__init__-methods-to-work-with-twisted-deferreds/</link>
		<comments>http://blogs.fluidinfo.com/terry/2009/05/11/a-mixin-class-allowing-python-__init__-methods-to-work-with-twisted-deferreds/#comments</comments>
		<pubDate>Mon, 11 May 2009 16:54:51 +0000</pubDate>
		<dc:creator>terry</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[twisted]]></category>
		<category><![CDATA[Deferred]]></category>
		<category><![CDATA[Twisted]]></category>
		<category><![CDATA[__init__]]></category>

		<guid isPermaLink="false">http://blogs.fluidinfo.com/terry/?p=579</guid>
		<description><![CDATA[I posted to the Python Twisted list back in Nov 2008 with subject: A Python metaclass for Twisted allowing __init__ to return a Deferred Briefly, I was trying to find a nice way to allow the __init__ method of a class to work with deferreds in such a way that methods of the class could [...]]]></description>
			<content:encoded><![CDATA[<p>I posted to <a href="http://twistedmatrix.com/pipermail/twisted-python/">the Python Twisted list</a> back in Nov 2008 with subject: A Python metaclass for <a href="http://twistedmatrix.com/">Twisted</a> allowing <code>__init__</code> to return a Deferred</p>
<p>Briefly, I was trying to find a nice way to allow the <code>__init__</code> method of a class to work with deferreds in such a way that methods of the class could use work done by <code>__init__</code> safe in the knowledge that the deferreds had completed.  E.g., if you have</p>
<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">class</span> X<span class="br0">&#40;</span><span class="kw2">object</span><span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; <span class="kw1">def</span> <span class="kw4">__init__</span><span class="br0">&#40;</span><span class="kw2">self</span>, host, port<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">def</span> final<span class="br0">&#40;</span>connection<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span>.<span class="me1">db</span> = connection<br />
&nbsp; &nbsp; &nbsp; &nbsp; d = makeDBConnection<span class="br0">&#40;</span>host, port<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; d.<span class="me1">addCallback</span><span class="br0">&#40;</span>final<span class="br0">&#41;</span></p>
<p>&nbsp; &nbsp; <span class="kw1">def</span> query<span class="br0">&#40;</span><span class="kw2">self</span>, q<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> <span class="kw2">self</span>.<span class="me1">db</span>.<span class="me1">runQuery</span><span class="br0">&#40;</span>q<span class="br0">&#41;</span><br />
&nbsp;</div>
<p>Then when you make an X and call query on it, there&#8217;s a chance the deferred wont have fired, and you&#8217;ll get an error.  This is just a very simple illustrative example.  There are many more, and this is a general problem of the synchronous world (in which <code>__init__</code> is supposed to prepare a fully-fledged class instance and cannot return a deferred) meeting the asynchronous world in which, as Twisted programmers, we would like to (and must) use deferreds.</p>
<p>The earlier thread, with lots of useful followups <a href="http://twistedmatrix.com/pipermail/twisted-python/2008-November/018600.html">can be read here</a>. Although I learned a lot in that thread, I wasn&#8217;t completely happy with any of the solutions. Some of the things that still bugged me are in posts towards the end of the thread (<a href="http://twistedmatrix.com/pipermail/twisted-python/2008-November/018624.html">here</a> and <a href="http://twistedmatrix.com/pipermail/twisted-python/2008-November/018634.html">here</a>).</p>
<p>The various approaches we took back then all boiled down to waiting for a deferred to fire before the class instance was fully ready to use. When that happened, you had your instance and could call its methods.</p>
<p>I had also thought about an alternate approach: having <code>__init__</code> add a callback to the deferreds it dealt with to set a flag in self and then have all dependent methods check that flag to see if the class instance was ready for use. But that 1) is ugly (too much extra code); 2) means the caller has to be prepared to deal with errors due to the class instance not being ready, and 3) adds a check to every method call. It would look something like this:</p>
<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">class</span> X<span class="br0">&#40;</span><span class="kw2">object</span><span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; <span class="kw1">def</span> <span class="kw4">__init__</span><span class="br0">&#40;</span><span class="kw2">self</span>, host, port<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span>.<span class="me1">ready</span> = <span class="kw2">False</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">def</span> final<span class="br0">&#40;</span>connection<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span>.<span class="me1">db</span> = connection<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span>.<span class="me1">ready</span> = <span class="kw2">True</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; d = makeDBConnection<span class="br0">&#40;</span>host, port<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; d.<span class="me1">addCallback</span><span class="br0">&#40;</span>final<span class="br0">&#41;</span></p>
<p>&nbsp; &nbsp; <span class="kw1">def</span> query<span class="br0">&#40;</span><span class="kw2">self</span>, q<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">if</span> <span class="kw1">not</span> <span class="kw2">self</span>.<span class="me1">ready</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">raise</span> IAmNotReadyException<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> <span class="kw2">self</span>.<span class="me1">db</span>.<span class="me1">runQuery</span><span class="br0">&#40;</span>q<span class="br0">&#41;</span><br />
&nbsp;</div>
<p>That was too ugly for my taste, for all of the above reasons, most especially for forcing the unfortunate caller of my code to handle <code>IAmNotReadyException</code>.</p>
<p>Anyway&#8230;. fast forward 6 months and I&#8217;ve hit the same problem again. It&#8217;s with existing code, in which I would like an <code>__init__</code> to call something that (now, due to changes elsewhere) returns a deferred. So I started thinking again, and came up with a much cleaner way to do the alternate approach via a class mixin:</p>
<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">from</span> twisted.<span class="me1">internet</span> <span class="kw1">import</span> defer</p>
<p><span class="kw1">class</span> deferredInitMixin<span class="br0">&#40;</span><span class="kw2">object</span><span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; <span class="kw1">def</span> wrap<span class="br0">&#40;</span><span class="kw2">self</span>, d, *wrappedMethods<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span>.<span class="me1">waiting</span> = <span class="br0">&#91;</span><span class="br0">&#93;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span>.<span class="me1">stored</span> = <span class="br0">&#123;</span><span class="br0">&#125;</span></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">def</span> restore<span class="br0">&#40;</span>_<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">for</span> method <span class="kw1">in</span> <span class="kw2">self</span>.<span class="me1">stored</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">setattr</span><span class="br0">&#40;</span><span class="kw2">self</span>, method, <span class="kw2">self</span>.<span class="me1">stored</span><span class="br0">&#91;</span>method<span class="br0">&#93;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">for</span> d <span class="kw1">in</span> <span class="kw2">self</span>.<span class="me1">waiting</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d.<span class="me1">callback</span><span class="br0">&#40;</span><span class="kw2">None</span><span class="br0">&#41;</span></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">def</span> makeWrapper<span class="br0">&#40;</span>method<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">def</span> wrapper<span class="br0">&#40;</span>*args, **kw<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d = defer.<span class="me1">Deferred</span><span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d.<span class="me1">addCallback</span><span class="br0">&#40;</span><span class="kw1">lambda</span> _: <span class="kw2">self</span>.<span class="me1">stored</span><span class="br0">&#91;</span>method<span class="br0">&#93;</span><span class="br0">&#40;</span>*args, **kw<span class="br0">&#41;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span>.<span class="me1">waiting</span>.<span class="me1">append</span><span class="br0">&#40;</span>d<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> d<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> wrapper</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">for</span> method <span class="kw1">in</span> wrappedMethods:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span>.<span class="me1">stored</span><span class="br0">&#91;</span>method<span class="br0">&#93;</span> = <span class="kw2">getattr</span><span class="br0">&#40;</span><span class="kw2">self</span>, method<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">setattr</span><span class="br0">&#40;</span><span class="kw2">self</span>, method, makeWrapper<span class="br0">&#40;</span>method<span class="br0">&#41;</span><span class="br0">&#41;</span></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; d.<span class="me1">addCallback</span><span class="br0">&#40;</span>restore<span class="br0">&#41;</span><br />
&nbsp;</div>
<p>You use it as in the class Test below:</p>
<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">from</span> twisted.<span class="me1">internet</span> <span class="kw1">import</span> defer, reactor</p>
<p><span class="kw1">def</span> fire<span class="br0">&#40;</span>d, value<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; <span class="kw1">print</span> <span class="st0">&quot;I finally fired, with value&quot;</span>, value<br />
&nbsp; &nbsp; d.<span class="me1">callback</span><span class="br0">&#40;</span>value<span class="br0">&#41;</span></p>
<p><span class="kw1">def</span> late<span class="br0">&#40;</span>value<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; d = defer.<span class="me1">Deferred</span><span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; reactor.<span class="me1">callLater</span><span class="br0">&#40;</span><span class="nu0">1</span>, fire, d, value<span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="kw1">return</span> d</p>
<p><span class="kw1">def</span> called<span class="br0">&#40;</span>result, what<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; <span class="kw1">print</span> <span class="st0">&#8216;final callback of %s, result = %s&#8217;</span> % <span class="br0">&#40;</span>what, result<span class="br0">&#41;</span></p>
<p><span class="kw1">def</span> stop<span class="br0">&#40;</span>_<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; reactor.<span class="me1">stop</span><span class="br0">&#40;</span><span class="br0">&#41;</span></p>
<p>
<span class="kw1">class</span> Test<span class="br0">&#40;</span>deferredInitMixin<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; <span class="kw1">def</span> <span class="kw4">__init__</span><span class="br0">&#40;</span><span class="kw2">self</span><span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; d = late<span class="br0">&#40;</span><span class="st0">&#8216;Test&#8217;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; deferredInitMixin.<span class="me1">wrap</span><span class="br0">&#40;</span><span class="kw2">self</span>, d, <span class="st0">&#8216;f1&#8242;</span>, <span class="st0">&#8216;f2&#8242;</span><span class="br0">&#41;</span></p>
<p>&nbsp; &nbsp; <span class="kw1">def</span> f1<span class="br0">&#40;</span><span class="kw2">self</span>, arg<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">print</span> <span class="st0">&quot;f1 called with&quot;</span>, arg<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> late<span class="br0">&#40;</span>arg<span class="br0">&#41;</span></p>
<p>&nbsp; &nbsp; <span class="kw1">def</span> f2<span class="br0">&#40;</span><span class="kw2">self</span>, arg<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">print</span> <span class="st0">&quot;f2 called with&quot;</span>, arg<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> late<span class="br0">&#40;</span>arg<span class="br0">&#41;</span></p>
<p>
<span class="kw1">if</span> __name__ == <span class="st0">&#8216;__main__&#8217;</span>:<br />
&nbsp; &nbsp; t = Test<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; d1 = t.<span class="me1">f1</span><span class="br0">&#40;</span><span class="nu0">44</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; d1.<span class="me1">addCallback</span><span class="br0">&#40;</span>called, <span class="st0">&#8216;f1&#8242;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; d2 = t.<span class="me1">f1</span><span class="br0">&#40;</span><span class="nu0">33</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; d2.<span class="me1">addCallback</span><span class="br0">&#40;</span>called, <span class="st0">&#8216;f1&#8242;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; d3 = t.<span class="me1">f2</span><span class="br0">&#40;</span><span class="nu0">11</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; d3.<span class="me1">addCallback</span><span class="br0">&#40;</span>called, <span class="st0">&#8216;f2&#8242;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; d = defer.<span class="me1">DeferredList</span><span class="br0">&#40;</span><span class="br0">&#91;</span>d1, d2, d3<span class="br0">&#93;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; d.<span class="me1">addBoth</span><span class="br0">&#40;</span>stop<span class="br0">&#41;</span><br />
&nbsp; &nbsp; reactor.<span class="me1">run</span><span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp;</div>
<p>Effectively, the <code>__init__</code> of my Test class asks <code>deferredInitMixin</code> to temporarily wrap some of its methods. <code>deferredInitMixin</code> stores the original methods away and replaces each of them with a function that immediately returns a deferred.  So after <code>__init__</code> finishes, code that calls the now-wrapped methods of the class instance before the deferred has fired will get a deferred back as usual (but see * below). As far as they know, everything is normal.  Behind the scenes, <code>deferredInitMixin</code> has arranged for these deferreds to fire only after the deferred passed from <code>__init__</code> has fired.  Once that happens, <code>deferredInitMixin</code> also restores the original functions to the instance. As a result there is no overhead later to check a flag to see if the instance is ready to use. If the deferred from <code>__init__</code> happens to fire before any of the instance&#8217;s methods are called, it will simply restore the original methods.  Finally (obviously?) you only pass the method names to <code>deferredInitMixin</code> that depend on the deferred in <code>__init__</code> being done.</p>
<p>BTW, calling the methods passed to <code>deferredInitMixin</code> &#8220;wrapped&#8221; isn&#8217;t really accurate. They&#8217;re just temporarily replaced.</p>
<p>I quite like this approach.  It&#8217;s a second example of something I posted about <a href="http://twistedmatrix.com/pipermail/twisted-python/2009-April/019522.html">here</a>, in which a pool of deferreds is accumulated and all fired when another deferred fires. It&#8217;s nice because you don&#8217;t reply with an error and there&#8217;s no need for locking or other form of coordination &#8211; the work you need done is already in progress, so you get back a fresh deferred and everything goes swimmingly.</p>
<p>* Minor note: the methods you wrap should probably be ones that already return deferreds. That way you always get a deferred back from them, whether they&#8217;re temporarily wrapped or not. The above mixin works just fine if you ask it to wrap non-deferred-returning functions, but you have to deal with the possibility that they will return a deferred (i.e., if you call them while they&#8217;re wrapped).</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.fluidinfo.com/terry/2009/05/11/a-mixin-class-allowing-python-__init__-methods-to-work-with-twisted-deferreds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Python metaclass for Twisted allowing __init__ to return a Deferred</title>
		<link>http://blogs.fluidinfo.com/terry/2008/11/03/a-python-metaclass-for-twisted-allowing-__init__-to-return-a-deferred/</link>
		<comments>http://blogs.fluidinfo.com/terry/2008/11/03/a-python-metaclass-for-twisted-allowing-__init__-to-return-a-deferred/#comments</comments>
		<pubDate>Sun, 02 Nov 2008 23:33:01 +0000</pubDate>
		<dc:creator>terry</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[tech]]></category>
		<category><![CDATA[twisted]]></category>
		<category><![CDATA[Deferred]]></category>
		<category><![CDATA[metaclass]]></category>
		<category><![CDATA[Twisted]]></category>
		<category><![CDATA[__init__]]></category>

		<guid isPermaLink="false">http://blogs.fluidinfo.com/terry/?p=281</guid>
		<description><![CDATA[OK, I admit, this is geeky. But we&#8217;ve all run into the situation in which you&#8217;re using Python and Twisted, and you&#8217;re writing a new class and you want to call something from the __init method that returns a Deferred. This is a problem. The __init method is not allowed to return a value, let [...]]]></description>
			<content:encoded><![CDATA[<p>OK, I admit, this is geeky.</p>
<p>But we&#8217;ve all run into the situation in which you&#8217;re using <a href="http://www.python.org/">Python</a> and <a href="http://twistedmatrix.com/">Twisted</a>, and you&#8217;re writing a new class and you want to call something from the <code>__init</code> method that returns a Deferred. This is a problem. The <code>__init</code> method is not allowed to return a value, let alone a Deferred. While you could just call the Deferred-returning function from inside your <code>__init</code>, there&#8217;s no guarantee of when that Deferred will fire. Seeing as you&#8217;re in your <code>__init</code>  method, it&#8217;s a good bet that you need that function to have done its thing before you let anyone get their hands on an instance of your class.</p>
<p>For example, consider a class that provides access to a database table. You want the <code>__init__</code> method to create the table in the db if it doesn&#8217;t already exist. But if you&#8217;re using Twisted&#8217;s <code><a href="http://twistedmatrix.com/documents/current/api/twisted.enterprise.adbapi.html">twisted.enterprise.adbapi</a></code> class, the <code>runInteraction</code> method returns a Deferred. You can call it to create the tables, but you don&#8217;t want the instance of your class back in the hands of whoever&#8217;s creating it until the table is created. Otherwise they might call a method on the instance that expects the table to be there.</p>
<p>A cumbersome solution would be to add a callback to the Deferred you get back from <code>runInteraction</code> and have that callback add an attribute to <code>self</code> to indicate that it is safe to proceed. Then all your class methods that access the db table would have to check to see if the attribute was on <code>self</code>, and take some alternate action if not. That&#8217;s going to get ugly very fast <em>plus</em>, your caller has to deal with you potentially not being ready.</p>
<p>I ran into this problem a couple of days ago and after scratching my head for a while I came up with an idea for how to solve this pretty cleanly via a <a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html">Python metaclass</a>. Here&#8217;s the metaclass code:</p>
<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">from</span> twisted.<span class="me1">internet</span> <span class="kw1">import</span> defer</p>
<p><span class="kw1">class</span> TxDeferredInitMeta<span class="br0">&#40;</span><span class="kw2">type</span><span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; <span class="kw1">def</span> <span class="kw4">__new__</span><span class="br0">&#40;</span>mcl, classname, bases, classdict<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; hidden = <span class="st0">&#8216;__hidden__&#8217;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; instantiate = <span class="st0">&#8216;__instantiate__&#8217;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">for</span> name <span class="kw1">in</span> hidden, instantiate:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">if</span> name <span class="kw1">in</span> classdict:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">raise</span> <span class="kw2">Exception</span><span class="br0">&#40;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="st0">&#8216;Class %s contains an illegally-named %s method&#8217;</span> %<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#40;</span>classname, name<span class="br0">&#41;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">try</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; origInit = classdict<span class="br0">&#91;</span><span class="st0">&#8216;__init__&#8217;</span><span class="br0">&#93;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">except</span> <span class="kw2">KeyError</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; origInit = <span class="kw1">lambda</span> <span class="kw2">self</span>: <span class="kw2">None</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">def</span> newInit<span class="br0">&#40;</span><span class="kw2">self</span>, *args, **kw<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hiddenDict = <span class="kw2">dict</span><span class="br0">&#40;</span>args=args, kw=kw, <span class="kw4">__init__</span>=origInit<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">setattr</span><span class="br0">&#40;</span><span class="kw2">self</span>, hidden, hiddenDict<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">def</span> _instantiate<span class="br0">&#40;</span><span class="kw2">self</span><span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">def</span> addSelf<span class="br0">&#40;</span>result<span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> <span class="br0">&#40;</span><span class="kw2">self</span>, result<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hiddenDict = <span class="kw2">getattr</span><span class="br0">&#40;</span><span class="kw2">self</span>, hidden<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d = defer.<span class="me1">maybeDeferred</span><span class="br0">&#40;</span>hiddenDict<span class="br0">&#91;</span><span class="st0">&#8216;__init__&#8217;</span><span class="br0">&#93;</span>, <span class="kw2">self</span>,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; *hiddenDict<span class="br0">&#91;</span><span class="st0">&#8216;args&#8217;</span><span class="br0">&#93;</span>, **hiddenDict<span class="br0">&#91;</span><span class="st0">&#8216;kw&#8217;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> d.<span class="me1">addCallback</span><span class="br0">&#40;</span>addSelf<span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; classdict<span class="br0">&#91;</span><span class="st0">&#8216;__init__&#8217;</span><span class="br0">&#93;</span> = newInit<br />
&nbsp; &nbsp; &nbsp; &nbsp; classdict<span class="br0">&#91;</span>instantiate<span class="br0">&#93;</span> = _instantiate<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> <span class="kw2">super</span><span class="br0">&#40;</span>TxDeferredInitMeta, mcl<span class="br0">&#41;</span>.<span class="kw4">__new__</span><span class="br0">&#40;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mcl, classname, bases, classdict<span class="br0">&#41;</span><br />
&nbsp;</div>
<p>I&#8217;m not going to explain what it does here. If it&#8217;s not clear and you want to know, send me mail or post a comment. But I&#8217;ll show you how you use it in practice. It&#8217;s kind of weird, but it makes sense once you get used to it.</p>
<p>First, we make a class whose metaclass is TxDeferredInitMeta and whose <code>__init__</code> method returns a deferred:</p>
<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">class</span> MyClass<span class="br0">&#40;</span><span class="kw2">object</span><span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; <span class="kw4">__metaclass__</span> = TxDeferredInitMeta<br />
&nbsp; &nbsp; <span class="kw1">def</span> <span class="kw4">__init__</span><span class="br0">&#40;</span><span class="kw2">self</span><span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; d = aFuncReturningADeferred<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> d<br />
&nbsp;</div>
<p>Having <code>__init__</code> return anything other than <code>None</code> is illegal in normal Python classes. But this is not a normal Python class, as you will now see.</p>
<p>Given our class, we use it like this:</p>
<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">def</span> cb<span class="br0">&#40;</span><span class="br0">&#40;</span>instance, result<span class="br0">&#41;</span><span class="br0">&#41;</span>:<br />
&nbsp; &nbsp; <span class="co1"># instance is an instance of MyClass</span><br />
&nbsp; &nbsp; <span class="co1"># result is from the callback chain of aFuncReturningADeferred</span><br />
&nbsp; &nbsp; <span class="kw1">pass</span></p>
<p>d = MyClass<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
d.__instantiate__<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
d.<span class="me1">addCallback</span><span class="br0">&#40;</span>cb<span class="br0">&#41;</span><br />
&nbsp;</div>
<p>That may look pretty funky, but if you&#8217;re used to Twisted it wont seem too bizarre. What&#8217;s happening is that when you ask to make an instance of MyClass, you get back an instance of a regular Python class. It has a method called <code>__instantiate__</code> that returns a Deferred. You add a callback to that Deferred and that callback is eventually passed two things. The first is an instance of MyClass, as you requested. The second is the result that came down the callback chain from the Deferred that was returned by the <code>__init__</code> method you wrote in MyClass.</p>
<p>The net result is that you have the value of the Deferred and you have your instance of MyClass. It&#8217;s safe to go ahead and use the instance because you know the Deferred has been called.  It will probably seem a bit odd to get your instance later as a result of a Deferred firing, but that&#8217;s perfectly in keeping with the Twisted way.</p>
<p>That&#8217;s it for now. You can grab the code and a <a href="http://twistedmatrix.com/documents/current/api/twisted.trial.html">trial</a> test suite to put it through its paces at <a href="http://foss.fluidinfo.com/txDeferredInitMeta.zip">http://foss.fluidinfo.com/txDeferredInitMeta.zip</a>. The code could be cleaned up somewhat, and made more general. There is a caveat to using it &#8211; your class can&#8217;t have <code>__hidden__</code> or <code>__instantiate__</code> methods. That could be improved. But I&#8217;m not going to bother for now, unless someone cares.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.fluidinfo.com/terry/2008/11/03/a-python-metaclass-for-twisted-allowing-__init__-to-return-a-deferred/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

