<?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>Atomized &#187; python</title>
	<atom:link href="http://atomized.org/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://atomized.org</link>
	<description>Fragmenting reality.</description>
	<lastBuildDate>Tue, 31 Aug 2010 18:00:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Debug Tracing Cassandra With Lazyboy</title>
		<link>http://atomized.org/2010/02/debug-tracing-cassandra-with-lazyboy/</link>
		<comments>http://atomized.org/2010/02/debug-tracing-cassandra-with-lazyboy/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 15:07:40 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[lazyboy]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://atomized.org/?p=690</guid>
		<description><![CDATA[Lazyboy 0.7.5 (which I just released) has a pretty great new feature, debug tracing. This is a great way to see what your application is doing and how long it takes. Using the debug trace facility is simple: import lazyboy as lzb lzb.add_pool('Keyspace', servers=['127.0.0.1:9160'], debug=True, slow_thresh=100) conn = lzb.get_pool('Keyspace') What this does is return a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://github.com/digg/lazyboy/tree/lazyboy-0.7.5">Lazyboy 0.7.5</a> (which I just released) has a pretty great new feature, debug tracing. This is a great way to see what your application is doing and how long it takes. Using the debug trace facility is simple:</p>
<pre class="src src-python"><span style="color: #7f007f;">import</span> lazyboy <span style="color: #7f007f;">as</span> lzb

lzb.add_pool(<span style="color: #8b2252;">'Keyspace'</span>, servers=[<span style="color: #8b2252;">'127.0.0.1:9160'</span>], debug=<span style="color: #7f007f;">True</span>,
           slow_thresh=100)
<span style="color: #a0522d;">conn</span> = lzb.get_pool(<span style="color: #8b2252;">'Keyspace'</span>)
</pre>
<p>What this does is return a connection object with tracing enabled. Every call made to Cassandra will be logged at the <code>DEBUG</code> level, and any call which takes longer than <code>slow_thresh</code> milliseconds will be logged at the <code>WARNING</code> level. When you use Lazyboy, you’ll see logs in this form:</p>
<pre class="src src-python">lzb.slice_iterator(lzb.Key(<span style="color: #8b2252;">"Keyspace"</span>, <span style="color: #8b2252;">"ColumnFamily"</span>, <span style="color: #8b2252;">"RowKey"</span>), count=1)

<span style="color: #b22222;"># -&gt; DEBUG:DebugTraceClient:72ms: 127.0.0.1:9160 -&gt; get_slice(('Keyspace', 'RowKey', {'column_family': 'ColumnFamily', 'keyspace': 'Keyspace', 'super_column': None, 'key': 'RowKey'}, SlicePredicate(column_names=None, slice_range=SliceRange(count=1, start='', reversed=False, finish='')), 1), {})
</span>
lzb.slice_iterator(lzb.Key(<span style="color: #8b2252;">"Keyspace"</span>, <span style="color: #8b2252;">"ColumnFamily"</span>, <span style="color: #8b2252;">"RowKey"</span>))

<span style="color: #b22222;"># -&gt; WARNING:DebugTraceClient:861ms: 127.0.0.1:9160 -&gt; get_slice(('Keyspace', 'RowKey', {'column_family': 'ColumnFamily', 'keyspace': 'Keyspace', 'super_column': None, 'key': 'RowKey'}, SlicePredicate(column_names=None, slice_range=SliceRange(count=10000, start='', reversed=False, finish='')), 1), {})
</span></pre>
<p>This should be pretty self-explanatory. You can see what calls were made to the Thrift client, the exact arguments, and how long it took. If you’d like to use a custom logger, you can pass a logging instance in the <code>log</code> keyword:</p>
<pre class="src src-python"><span style="color: #7f007f;">import</span> logging

lzb.add_pool(<span style="color: #8b2252;">'Keyspace'</span>, servers=[<span style="color: #8b2252;">'127.0.0.1:9160'</span>], debug=<span style="color: #7f007f;">True</span>,
           slow_thresh=100, log=logging.getLogger(<span style="color: #8b2252;">'Lazyboy'</span>))
<span style="color: #a0522d;">conn</span> = lzb.get_pool(<span style="color: #8b2252;">'Keyspace'</span>)
</pre>
<p>You might want to do this to enable debugging, since the default logger configuration is set higher than <code>DEBUG</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://atomized.org/2010/02/debug-tracing-cassandra-with-lazyboy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>pep8 &amp; pylint in Emacs</title>
		<link>http://atomized.org/2010/02/pep8-pylint-in-emacs/</link>
		<comments>http://atomized.org/2010/02/pep8-pylint-in-emacs/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 19:02:00 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://atomized.org/?p=685</guid>
		<description><![CDATA[I do a lot of hacking on Python these days, and of course, I use Emacs. The built-in python-mode has the ability to run pychecker on your source, but doesn&#8217;t integrate other tools. I like to run pep8.py &#038; pylint regularly to keep my code clean, so I hacked together compilation-derived modes to drive them. [...]]]></description>
			<content:encoded><![CDATA[<p>I do a lot of hacking on Python these days, and of course, I use Emacs. The built-in python-mode has the ability to run pychecker on your source, but doesn&#8217;t integrate other tools. I like to run pep8.py &#038; pylint regularly to keep my code clean, so I hacked together compilation-derived modes to drive them.</p>
<p>Compile.el is really great for this kind of thing, since it lets you quickly navigate over the lines mentioned in the program&#8217;s output. It&#8217;s quite efficient, and I enjoy it immensely. One note of interest: pep8.py doesn&#8217;t output line numbers in order, which confuses compile-mode. I just pipe the output through sort to work around this.</p>
<p>The code is on GitHub: <a href="http://gist.github.com/302847">python-pep8.el</a> and <a href="http://gist.github.com/302848">python-pylint.el</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://atomized.org/2010/02/pep8-pylint-in-emacs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>When lexical scoping attacks</title>
		<link>http://atomized.org/2009/06/when-lexical-scoping-attacks/</link>
		<comments>http://atomized.org/2009/06/when-lexical-scoping-attacks/#comments</comments>
		<pubDate>Tue, 30 Jun 2009 21:30:34 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scope]]></category>
		<category><![CDATA[wtf]]></category>

		<guid isPermaLink="false">http://atomized.org/?p=574</guid>
		<description><![CDATA[Consider the following Python code: bar = [] def test(): new = ['this', 'comes', 'from', 'test'] bar.extend(new) print bar print bar test() print bar This code generates this output: [] ['this', 'comes', 'from', 'test'] ['this', 'comes', 'from', 'test'] Which is to say, bar is empty before test(), has the contents of new inside of test(), [...]]]></description>
			<content:encoded><![CDATA[<p>Consider the following Python code:</p>
<pre language="python">
bar = []
def test():
    new = ['this', 'comes', 'from', 'test']
    bar.extend(new)
    print bar

print bar
test()
print bar
</pre>
<p>This code generates this output:</p>
<pre>
[]
['this', 'comes', 'from', 'test']
['this', 'comes', 'from', 'test']
</pre>
<p>Which is to say, <code>bar</code> is empty before <code>test()</code>, has the contents of <code>new</code> inside of <code>test()</code>, and continues to have that value when <code>test()</code> returns.</p>
<p>Now, look at this code:</p>
<pre language="python">
bar = []
def test():
    new = ['this', 'comes', 'from', 'test']
    bar = new
    print bar

print bar
test()
print bar
</pre>
<p>Which outputs:</p>
<pre>
[]
['this', 'comes', 'from', 'test']
[]
</pre>
<p>The value of <code>bar</code> is only changed inside <code>test()</code>. Upon further reflection, I realized that the assignment was assigning a new local variable inside the <code>test()</code> scope, whereas accessing <code>bar</code> returns the variable from the outer scope, which is then modified.</p>
<p>This behavior doesn’t make a whole lot of sense to me.</p>
]]></content:encoded>
			<wfw:commentRss>http://atomized.org/2009/06/when-lexical-scoping-attacks/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Abbrevs in the REPL</title>
		<link>http://atomized.org/2009/06/abbrevs-in-the-repl/</link>
		<comments>http://atomized.org/2009/06/abbrevs-in-the-repl/#comments</comments>
		<pubDate>Fri, 12 Jun 2009 18:01:39 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[abbrev]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://atomized.org/?p=571</guid>
		<description><![CDATA[I love abbrevs, and I use them all the time. While I prefer yasnippet for more complex things, abbrevs are great. I use them for simple (1-5 word) expansions, and they’re particularly helpful with SQL mode. One of my gripes is that when I define abbrevs for a programming mode like python-mode, the abbrevs don’t [...]]]></description>
			<content:encoded><![CDATA[<p>I love <a href="http://www.emacswiki.org/emacs/AbbrevMode">abbrevs</a>, and I use them all the time. While I prefer <a href="http://code.google.com/p/yasnippet/">yasnippet</a> for more complex things, abbrevs are great. I use them for simple (1-5 word) expansions, and they’re particularly helpful with SQL mode.</p>
<p>One of my gripes is that when I define abbrevs for a programming mode like <code>python-mode</code>, the abbrevs don’t get used when I use the REPL via <code>run-python</code>.</p>
<p>This is pretty straightforward to fix:</p>
<pre language="emacs-lisp">
(eval-after-load 'python
  '(progn
     (derived-mode-merge-abbrev-tables python-mode-abbrev-table
                                       inferior-python-mode-abbrev-table)))
</pre>
<p>This tells Emacs to merge the python-mode abbrevs into the inferior-python-mode abbrev table. Now, when I fire up Python in Emacs, I have all my usual abbrevs. This may be inadvisable if you’re using abbrev to hook into auto-insert or to trigger behavior which expects a non-interactive environment, but it’s perfect when you just want to type &#8220;imp&#8221; instead of &#8220;import.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://atomized.org/2009/06/abbrevs-in-the-repl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Disabling Python-mode’s skeletons</title>
		<link>http://atomized.org/2009/01/disabling-python-mode%e2%80%99s-skeletons/</link>
		<comments>http://atomized.org/2009/01/disabling-python-mode%e2%80%99s-skeletons/#comments</comments>
		<pubDate>Sat, 24 Jan 2009 20:59:43 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[abbrev]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[lisp]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[skeleton]]></category>

		<guid isPermaLink="false">http://atomized.org/?p=498</guid>
		<description><![CDATA[One of the few things I dislike about Emacs 23 is the new behavior of python-mode. When you type things like def, it expands these into snippets using abbrev-mode. I don’t like this because I have similar functionality by way of yasnippet. I prefer the yasnippet way because it uses fields in the snippet. The [...]]]></description>
			<content:encoded><![CDATA[<p>One of the few things I dislike about <a href="/wp-content/cocoa-emacs-nightly">Emacs 23</a> is the new behavior of <code>python-mode</code>. When you type things like <code>def</code>, it expands these into snippets using <code>abbrev-mode</code>. I don’t like this because I have similar functionality by way of <a href="http://code.google.com/p/yasnippet/">yasnippet</a>.</p>
<p>I prefer the yasnippet way because it uses fields in the snippet. The default way prompts you for values in the minibuffer with <code>read-string</code>, which I dislike. It also overrides my preferred behavior, and there’s no option to disable it.</p>
<p>Of course, there’s always a way in Emacs, and it can be removed with this code:</p>
<pre language="lisp">
(let (python-mode-abbrev-table)
  (require 'python))
</pre>
<p>Which is simple and works, though I dislike it. I prefer to tweak behaviors with <code>eval-after-load</code>, since <code>require</code>s can be slow. Unfortunately, by the time that code executes, the damage is done.</p>
<p>I’ll update if I find a better way to fix it.</p>
]]></content:encoded>
			<wfw:commentRss>http://atomized.org/2009/01/disabling-python-mode%e2%80%99s-skeletons/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Why Lisp is Awesome</title>
		<link>http://atomized.org/2009/01/why-lisp-is-awesome/</link>
		<comments>http://atomized.org/2009/01/why-lisp-is-awesome/#comments</comments>
		<pubDate>Sun, 11 Jan 2009 00:52:43 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[lisp]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://atomized.org/?p=475</guid>
		<description><![CDATA[A few weeks ago, I was talking to some people about the nerdy things I work on, and the nerdy things I like. The conversation inevitably turned to Emacs and Lisp, and someone asked why I liked them so much. There are a lot of reasons, but I think the main one is that it’s [...]]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago, I was talking to some people about the nerdy things I work on, and the nerdy things I like. The conversation inevitably turned to Emacs and Lisp, and someone asked why I liked them so much.</p>
<p>There are a lot of reasons, but I think the main one is that it’s such a pioneering and influential language, and most people aren’t aware of it. An astonishing number of language features we take for granted owe their existence to Lisp.</p>
<ul>
<li><b>The switch statement</b>. In lisp, this works like so:
<pre language="lisp">
(cond
    ((= var "foo")
     (message "This is the foo block."))
    ((= var "bar")
     (message "This is the bar block."))
    (t
     (message "Default case")))
</pre>
<p>This is equivalent to the following code in C:</p>
<pre language="c">
switch (var) {
    case "foo":
        printf("foo block.");
        break;

    case "bar":
        printf("bar block.");
        break;

    default:
        printf("Default case")
}
</pre>
<p>As you can see, they both have advantages and disadvantages:</p>
<ul>
<li>The lisp version is more succinct.</li>
<li>In lisp, you can test for any condition, whereas <del datetime="2010-01-07T00:56:33+00:00">C only lets you test one expression. This is a wash, since if you want multiple tests on the same expression, you have to repeat it throughout the <code>(cond)</code>.</del></li>
<li>There’s no way to fall through in lisp like there is in C.</li>
<li><del datetime="2010-01-07T00:56:33+00:00">…But, your condition can be an expression in Lisp, rather than a simple test for equality, so your condition could be <code>(cond (or "foo" "bar"))</code></del></li>
<li><ins datetime="2010-01-07T00:56:33+00:00">As a commenter points out, you can use <code>switch(true)</code> to test more complex expressions in your <code>case</cond>s. While this works, it feels pretty hacky.</ins></li>
</ul>
</li>
<li><b>Lambda functions.</b> One of the fundamental building blocks of Lisp, lambdas have gained widespread adoption in modern languages like JavaScript, PHP, Python, Perl, Visual Basic, Ruby, and C#.</li>
<li>Hand in hand with lambdas, <b>functions are data.</b> That is, you can pass a function to another function. A function can return a function. Using lambdas, a function can create an entirely new function, return it, and it may be passed to yet another function.</li>
<li><b>Closures.</b> In a nutshell, closures give you a private, inherited namespace. So if your parent closure defines a variable <code>x = 5</code>, and you create a closure inside it, you also can see that <code>x = 5</code>. If your closure changes that to <code>x = 50</code>, that is invisible to your parent closure, but visible (in the same way) to any closures that closure creates. Essentially, it’s a private copy-on-write namespace. Closures were first implemented in Scheme, a Lisp-descended language. Before that, the <code>let</code> expressions gave some of the flexibility of closures.
<pre language="lisp">
(defun print-foo ()
    (message foo))

(setq foo "Foo")
;; Calling (print-foo) will print "Foo".

;; Inside the let block, 'foo is changed to "bar".
;; Evaluating this prints "Bar".
(let ((foo "Bar"))
    (print-foo))

;; This prints "Foo" again
(print-foo)
</pre>
</li>
<li><b>Dynamic programming.</b> With <code>fset</code>, you can change any function. Common Lisp adds <code>flet</code>, which works the same as <code>let</code>, but on functions. So you can change how library code works at an extremely deep level, but keep those changes out of the way of other code which expects the stock behavior.</li>
<li><b>Data is code.</b> This is an extremely powerful concept, and it’s been seen more recently in JSON. The basic idea is that you leverage the language parser to parse complex data structures, rather than writing your own parser.
<pre language="lisp">
'((item-one . (foo bar ))
  (item-two . (baz quux)))
</pre>
<p>This is equavalent to</p>
<pre language="javascript">
{
    "item-one": ["foo" "bar"],
    "item-two": ["baz" "quux"]
}
</pre>
<p>In other words, your data is expressed in the same literal notation as if it was in your code.</li>
<li><b>And-or trick.</b> At least Python and Ruby have copied this feature. In Lisp, boolean expressions don’t evaluate to true or false; rather, they evaluate to the portion of the expression causing the test to pass or fail. This sounds much more complicated than it really is. Here’s are some sample expressions:
<pre language="c">
0 || 99;
</pre>
<p>In C, this will return <code>TRUE</code>; The zero is considered false, and non-zero is true. Since the condition is true, true is returned.</p>
<pre language="lisp">
(or nil 99)
</pre>
<p>The same test in lisp. Rather than return <code>t</code> (Lisp’s equivalent to C’s <code>TRUE</code>), this expression returns <code>99</code>. The value 99 is what caused the expression to terminate, so it’s value is returned.</p>
<p>It’s hard to understand the power of this at first, but consider the case where you want to assign the variable <code>x</code> the value of variable <code>a</code> if it is not false, or <code>b</code> otherwise. In C, you have:</p>
<pre language="c">
if (a) {
    x = a;
} else {
    x = b;
}
</pre>
<p>Not very elegant. You can use the ternary syntax, where it becomes:</p>
<pre language="c">
x = a ? a : b;
</pre>
<p>This is better, but note how you have to repeat the <code>a</code> variable twice. Contrast this with the lisp version:</p>
<pre language="lisp">
(setq x (or a b))
</pre>
<p>No repetition. While it’s actually longer than the C version in this simple example, you gain much benefit when you use more complex expressions, such as ones where you want to assign the return value of a function if it’s true. In C, you’re stuck with calling the method twice, or assigning it’s output to a variable before the test.</p>
<p>In Python, you’d use:</p>
<pre language="python">
x = a or b
</pre>
</li>
<li><b>References.</b> Lisp’s basic data structure is the linked list. What’s interesting is how they’re managed. Lisp lists are constructed from <i>cons cells</i>, where the first half (the <i>car</i>)points to the data for that cell, and the last half (the <i>cdr</i>, pronounced "coulder") points to the next cell; the last cell in the list has a null pointer. The really neat part of this is that <i>everything is a pointer</i>. So every member of a list exists on it’s own, and other lists are free to point to it. Consider this:
<pre language="lisp">
;; This sets 'ex to a two-element list: (foo bar)
(setq ex '(bar baz))

;; This creates a new list 'ey; the first cell is 'foo, and the rest of the
;; list is the contents of 'ex.
;; Evaluating 'ey will show: (foo bar baz)
(setq ey (cons 'foo ex))

;; This sets the first element of 'ex to quux
(setcar ex 'quux)

;; Evaluating ex now produces: (quux bar)
;; Evaluating ey produces: (foo quux bar)
    </pre>
<p>This works because ey’s cdr points to ex; it hasn’t copied ex, it’s incorporated it by reference.
    </li>
</ul>
<p>So there you have a short tour of what’s cool about Lisp, and the features you’re using that you owe to it. Not all of these features were in the earliest version of Lisp, but it’s quite a feat that so many advanced high-level language features first appeared there. <a href="http://www-formal.stanford.edu/jmc/recursive.html">The original paper on Lisp</a> is still quite relevant, and shows some of the algorithms you can implement with the earliest parts of the language.</p>
<p>I don’t mean to bash on C here; I actually really like C for what it is. And it’s not unlike Lisp in that it’s a highly influential language with an extremely simple core.</p>
<p>What’s fascinating to me about Lisp is that a language which is fifty years old is was so advanced, and is <i>still</i> so influential. In the fast-moving world of computing, that’s truly an amazing accomplishment.</p>
]]></content:encoded>
			<wfw:commentRss>http://atomized.org/2009/01/why-lisp-is-awesome/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Python on OS X Leopard lacks select.poll()</title>
		<link>http://atomized.org/2008/12/python-on-os-x-leopard-lacks-selectpoll/</link>
		<comments>http://atomized.org/2008/12/python-on-os-x-leopard-lacks-selectpoll/#comments</comments>
		<pubDate>Sun, 14 Dec 2008 21:09:26 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[select.poll]]></category>

		<guid isPermaLink="false">http://atomized.org/?p=437</guid>
		<description><![CDATA[I was trying to get phpsh working the other day, and it kept dying with Traceback (most recent call last): File "./phpsh", line 329, in &#60;module&#62; select.poll().register(p.stderr) AttributeError: 'module' object has no attribute 'poll' As it turns out, Python as shipped with Mac OS X Leopard was compiled without select.poll(). I have no idea why, [...]]]></description>
			<content:encoded><![CDATA[<p>I was trying to get <a href="http://www.phpsh.org/">phpsh</a> working the other day, and it kept dying with</p>
<pre>
Traceback (most recent call last):
 File "./phpsh", line 329, in &lt;module&gt;
   select.poll().register(p.stderr)
AttributeError: 'module' object has no attribute 'poll'
</pre>
<p>As it turns out, Python as shipped with Mac OS X Leopard was compiled without <code>select.poll()</code>. I have no idea why, but it’s most irritating. It’s also perhaps the only good reason to use something like <a href="http://www.macports.org/">MacPorts</a>, which <a href="http://atomized.org/2008/09/the-thing-i-hate-about-macports/">I have complained about before</a>.</p>
<p>I’ve reported the bug to Apple as <a href="https://bugreport.apple.com/cgi-bin/WebObjects/RadarWeb.woa/79/wo/770dASh8Oc35SCLA7kMd8w/8.34">#6444485</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://atomized.org/2008/12/python-on-os-x-leopard-lacks-selectpoll/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Parsing URL query parameters in Python</title>
		<link>http://atomized.org/2008/06/parsing-url-query-parameters-in-python/</link>
		<comments>http://atomized.org/2008/06/parsing-url-query-parameters-in-python/#comments</comments>
		<pubDate>Mon, 02 Jun 2008 23:22:33 +0000</pubDate>
		<dc:creator>Ian</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://atomized.org/?p=264</guid>
		<description><![CDATA[I’ve been dabbling with Python for several months now, but I’m not quite as proficient with it as I’d like. I was hacking on some stuff recently, and needed to parse the query parameters in a URL. Python has URL parsing, but it doesn’t include querystring parsing. This was the pleasantly easy solution: from urlparse [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve been dabbling with <a href="http://python.org">Python</a> for several months now, but I’m not quite as proficient with it as I’d like.</p>
<p>I was hacking on some stuff recently, and needed to parse the query parameters in a URL. Python has <a href="http://docs.python.org/lib/module-urlparse.html">URL parsing</a>, but it doesn’t include querystring parsing.</p>
<p>This was the pleasantly easy solution:</p>
<pre>
from urlparse import urlparse
url = urlparse('http://www.google.com/search?hl=en&#038;safe=off&#038;q=atomized&#038;btnG=Search')
params = dict([part.split('=') for part in url[4].split('&#038;')])
</pre>
<h2>What’s going on here</h2>
<p>Let’s break the example down a bit.</p>
<ol>
<li>
<pre>from urlparse import urlparse</pre>
<p>This pulls in Python’s URL parser.</p>
</li>
<li>
<pre>url = urlparse('http://www.google.com/search?hl=en&#038;safe=off&#038;q=atomized&#038;btnG=Search')</pre>
<p>This passes the URL through urlparse, leaving us with a <a href="http://en.wikipedia.org/wiki/Tuple">tuple</a> of URL components.</p>
</li>
<li>
<pre>url[4].split('&#038;')</pre>
<p>This splits the querystring on “&#038;” characters, leaving us with a list of “key=val” scalars. The output of this would be:</p>
<pre>['hl=en', 'safe=off', 'q=atomized', 'btnG=Search']</pre>
<p></li>
<li>
<pre>[part.split('=') for part in url[4].split('&#038;')]</pre>
<p>This is Python’s <a href="http://diveintopython.org/native_data_types/mapping_lists.html">list mapping</a>, also known as <a href="http://en.wikipedia.org/wiki/List_comprehension">list comprehension</a>. It allows us to map a function over a list &#8211; in this case, <code>part.split('=')</code> on the list of “key=value” pairs from the previous step. This leaves us with:</p>
<pre>[['hl', 'en'], ['safe', 'off'], ['q', 'atomized'], ['btnG', 'Search']]</pre>
<p>That is, an array of arrays, where the first member of the child array is the key and the second is the value.</p>
</li>
<li>
<pre>params = dict([part.split('=') for part in url[4].split('&#038;')])</pre>
<p>The last part of this is <code>dict()</code>, which turns the array structure above into a dictionary:</p>
<pre>
{'q': 'atomized', 'safe': 'off', 'btnG': 'Search', 'hl': 'en'}
</pre>
<p>Thix is roughly equivalent to a hash map or associative array. It allows us to access specific keys, such as <code>params['q']</code>.</p>
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://atomized.org/2008/06/parsing-url-query-parameters-in-python/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
