<?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>Zeroth Code &#187; python tricks</title>
	<atom:link href="http://www.oddco.ca/zeroth/zblog/category/python-tricks/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.oddco.ca/zeroth/zblog</link>
	<description>Game design, development, technology, programming, and python</description>
	<lastBuildDate>Thu, 09 Sep 2010 14:18:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Python Tricks: Advanced String Formatting</title>
		<link>http://www.oddco.ca/zeroth/zblog/2009/04/22/python-tricks-advanced-string-formatting/</link>
		<comments>http://www.oddco.ca/zeroth/zblog/2009/04/22/python-tricks-advanced-string-formatting/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 17:08:41 +0000</pubDate>
		<dc:creator>Zeroth</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[python tricks]]></category>

		<guid isPermaLink="false">http://www.oddco.ca/zeroth/zblog/?p=184</guid>
		<description><![CDATA[I ran across this a long time ago, never really used it till more recently, but it really shows the power and capability of Python. So, say you have a big set of local variables which need to go into the string you are building, say for a YAPWF(Yet Another Python Web Framework). Thats means [...]]]></description>
			<content:encoded><![CDATA[<p>I ran across this a long time ago, never really used it till more recently, but it really shows the power and capability of Python.</p>
<p>So, say you have a big set of local variables which need to go into the string you are building, say for a YAPWF(Yet Another Python Web Framework).</p>
<p>Thats means you have this messy looking code:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">s=<span style="color: #483d8b;">&quot;%d%f&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>car, calc<span style="color: black;">&#41;</span></pre></div></div>

<p>Its messy, because you&#8217;ve separated contextual information from the actual place that it matters, and if the string is very long and confusing, it gets messy, and opens you up to errors down the road. In addition, you are tied to having those variables exist locally.</p>
<p>However, there is a much, much nicer way to do this.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">d=<span style="color: black;">&#123;</span><span style="color: #483d8b;">&quot;number&quot;</span>:<span style="color: #ff4500;">100</span>, <span style="color: #483d8b;">&quot;float&quot;</span>:<span style="color: #ff4500;">4.2</span>, <span style="color: #483d8b;">&quot;status&quot;</span>:<span style="color: #483d8b;">&quot;okay&quot;</span>, <span style="color: #483d8b;">&quot;ph&quot;</span>:<span style="color: #ff4500;">8665782</span><span style="color: black;">&#125;</span>
s=<span style="color: #483d8b;">&quot;%(number)d%(float)f%(status)s%(ph)d&quot;</span> <span style="color: #66cc66;">%</span> d
<span style="color: #ff7700;font-weight:bold;">print</span> s
1004.2okay8665782</pre></div></div>

<p>What this means is now you can throw in each of the relevant possible variables into the key that matters into a single dictionary object, and pass that around easily. The only thing you&#8217;re tied to now are the keys of the dictionary, giving you a bit of Adapter action.</p>
<p>Just one note, the format goes like this:</p>
<pre>"%({key name}){format modifier}" % dictionary</pre>
<p>As well, you can name the keys relevant names, like status, phone, etc, and your string formatting becomes a lot easier to read.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.oddco.ca/zeroth/zblog/2009/04/22/python-tricks-advanced-string-formatting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Changing types in Python</title>
		<link>http://www.oddco.ca/zeroth/zblog/2008/12/10/changing-types-in-python/</link>
		<comments>http://www.oddco.ca/zeroth/zblog/2008/12/10/changing-types-in-python/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 23:54:09 +0000</pubDate>
		<dc:creator>Zeroth</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[python tricks]]></category>

		<guid isPermaLink="false">http://www.oddco.ca/zeroth/zblog/?p=161</guid>
		<description><![CDATA[Okay, so its another entry in my long-abandoned python tricks series. First, lets take a look at a couple of classes: class B&#40;object&#41;: def foo&#40;self&#41;: return '10' &#160; class A&#40;object&#41;: def __init__&#40;self&#41;: self.a='a' def foo&#40;self&#41;: return '1' The important part here is the (object) subclassing. This trick only works if you do that. Lets take [...]]]></description>
			<content:encoded><![CDATA[<p>Okay, so its another entry in my long-abandoned python tricks series.</p>
<p>First, lets take a look at a couple of classes:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> B<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> foo<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">'10'</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> A<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">a</span>=<span style="color: #483d8b;">'a'</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> foo<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">'1'</span></pre></div></div>

<p>The important part here is the (object) subclassing. This trick only works if you do that. Lets take alook at it in operation:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #66cc66;">&gt;&gt;&gt;</span> a=A<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a
<span style="color: #66cc66;">&lt;</span>changetype.<span style="color: black;">A</span> <span style="color: #008000;">object</span> at 0x7f0f18dbf9d0<span style="color: #66cc66;">&gt;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a.__class__
<span style="color: #66cc66;">&lt;</span>class <span style="color: #483d8b;">'A'</span><span style="color: #66cc66;">&gt;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a.<span style="color: black;">a</span>
<span style="color: #483d8b;">'a'</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a.<span style="color: black;">foo</span>
<span style="color: #66cc66;">&lt;</span>bound method A.<span style="color: black;">foo</span> of <span style="color: #66cc66;">&lt;</span>changetype.<span style="color: black;">A</span> <span style="color: #008000;">object</span> at 0x7f0f18dbf9d0<span style="color: #66cc66;">&gt;&gt;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a.<span style="color: black;">foo</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #483d8b;">'1'</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a.__class__=B
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a.<span style="color: black;">a</span>
<span style="color: #483d8b;">'a'</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a.<span style="color: black;">foo</span>
<span style="color: #66cc66;">&lt;</span>bound method B.<span style="color: black;">foo</span> of <span style="color: #66cc66;">&lt;</span>changetype.<span style="color: black;">B</span> <span style="color: #008000;">object</span> at 0x7f0f18dbf9d0<span style="color: #66cc66;">&gt;&gt;</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> a.<span style="color: black;">foo</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #483d8b;">'10'</span>
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #008000;">isinstance</span><span style="color: black;">&#40;</span>a, B<span style="color: black;">&#41;</span>
<span style="color: #008000;">True</span></pre></div></div>

<p>As you can see, I was able to override the foo() method with the one in the Beta class. As well, this only works on instanced objects. Now, what use is this you may ask? It is basically meta-programming. For 90% of programming tasks, meta-programming is not needed at all. But for that remaining 10%, you can do some seriously cool stuff, like changing the operation of a class during runtime, without modifying the class variables.</p>
<p>As a real-life example, I just finished writing a simplistic query parser. I realized I had forgetten to take into account price queries, so, I created a PriceToken class, that on instantiation, changes its own class to that of a TermToken. Otherwise, I would have had to rewrite about 100 lines of code to allow the use of a PriceToken. Pretty much useful because I&#8217;m lazy. But, yes, in Python, you can change the type of an object on the fly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.oddco.ca/zeroth/zblog/2008/12/10/changing-types-in-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Functional for the win</title>
		<link>http://www.oddco.ca/zeroth/zblog/2008/06/19/functional-for-the-win/</link>
		<comments>http://www.oddco.ca/zeroth/zblog/2008/06/19/functional-for-the-win/#comments</comments>
		<pubDate>Thu, 19 Jun 2008 20:53:31 +0000</pubDate>
		<dc:creator>Zeroth</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[python tricks]]></category>

		<guid isPermaLink="false">http://www.oddco.ca/zeroth/zblog/?p=81</guid>
		<description><![CDATA[As part of my new job, as a research student, I have to process a lot of data. On the order of several hundreds of thousands of records. So, I turned to my favourite language, Python. Its what caused my earlier issues with memory management. A few more lessons I&#8217;ve learned: sometimes theres a faster [...]]]></description>
			<content:encoded><![CDATA[<p>As part of my new job, as a research student, I have to process a lot of data. On the order of several hundreds of thousands of records. So, I turned to my favourite language, Python. Its what caused my earlier issues with memory management.</p>
<p>A few more lessons I&#8217;ve learned:</p>
<ul>
<li>sometimes theres a faster way to do stuff.</li>
<li>make sure you aren&#8217;t putting repetitive data into a database</li>
<li>verify the data format before you download 2-3 GB of it</li>
</ul>
<p>Okay, so, faster way to do stuff. Python has both a performance advantage and disadvantage. The advantage is that it only takes one or two hours to code up something to process data. The disadvantage is that in an effort to be clear and simple, one can end up coding a task that takes 20-100x longer than it should. Like I did.</p>
<p>I had a lot of nested loops, python speed loops, involving lots of duplicate handling, inserting to a database, etc. It took five hours to go through  only 14 sets of queries to clear out. I had a lot of duplicate rows that needed to be erased. For a query looking for rows with an id of 15, there are 25,607 records. Removing the duplicates yields&#8230; 807. Brilliant.</p>
<p>Today, I decided to take most of the loops, and replace them with their functional counterparts, map, lambda, and Google&#8217;s functional tools in python,  goopy. In only two hours, it has gone through now, 160 ids. In less than half the time. Pretty amazing, eh?</p>
<p>Here&#8217;s a sample:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">for</span> row <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">all</span>:
     curs=curs.<span style="color: black;">execute</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'insert into elements2 values(?, ?, ?, ?, ?)'</span>, <span style="color: black;">&#40;</span>row<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>, row<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>, <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>row<span style="color: black;">&#91;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>, <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>row<span style="color: black;">&#91;</span><span style="color: #ff4500;">3</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>, <span style="color: #483d8b;">''</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>replaced with:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #008000;">map</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> row: <span style="color: #66cc66;">&lt;</span>code<span style="color: #66cc66;">&gt;</span>conn.<span style="color: black;">execute</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'insert into elements2 values(?, ?, ?, ?, ?)'</span>, <span style="color: black;">&#40;</span>row<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>, row<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>, <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>row<span style="color: black;">&#91;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>, <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>row<span style="color: black;">&#91;</span><span style="color: #ff4500;">3</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>, <span style="color: #483d8b;">''</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">&lt;</span>/code<span style="color: #66cc66;">&gt;</span>, <span style="color: #008000;">all</span><span style="color: black;">&#41;</span></pre></div></div>

<p>A little bit more difficult to read, yes, but, the speed improvements are well over 50 times faster&#8230;</p>
<p>All this work to clear out duplicate entries, and how intensive it can be to fix, is a perfect example of why the &#8220;Look Before You leap&#8221; programming paradigm works better than, &#8220;Ask for Forgiveness Not Permission&#8221;.</p>
<p>Now, once the processing is done, I&#8217;ll be able to go through all the data&#8230; and add a piece of information I forgot to process in the first place to each entry. Yay me!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.oddco.ca/zeroth/zblog/2008/06/19/functional-for-the-win/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Memory management in Python</title>
		<link>http://www.oddco.ca/zeroth/zblog/2008/06/17/memory-management-in-python/</link>
		<comments>http://www.oddco.ca/zeroth/zblog/2008/06/17/memory-management-in-python/#comments</comments>
		<pubDate>Tue, 17 Jun 2008 21:43:12 +0000</pubDate>
		<dc:creator>Zeroth</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[python tricks]]></category>

		<guid isPermaLink="false">http://www.oddco.ca/zeroth/zblog/?p=80</guid>
		<description><![CDATA[Thats right, the dreaded two m&#8217;s. If you use C or C++, its quite dreaded. However, for about the first time ever, I ran into memory management issues in Python! Well, partially due to my own mistakes, and partially due to the way Python handles memory. Memory handling schemes go awry Well, not quite. More [...]]]></description>
			<content:encoded><![CDATA[<p>Thats right, the dreaded two m&#8217;s. If you use C or C++, its quite dreaded. However, for about the first time ever, I ran into memory management issues in Python! Well, partially due to my own mistakes, and partially due to the way Python handles memory.</p>
<h2>Memory handling schemes go awry</h2>
<p>Well, not quite. More like, a leaky abstraction, compounded by my own idiot mistakes in the code. When memory is allocated in a loop, it is normally a smart optimization to hold onto that memory. What this means is that there are some cool things that you can do, like, refer to variables that were allocated inside a loop, and they will be in the local scope. They will just have the latest value thats been assigned to that variable.</p>
<p>However, in my case it backfired. The memory was held onto&#8230; and never reused. Essentially, I had a memory leak.</p>
<h2>My own stupid mistakes</h2>
<p>What happened, is that I was loading in a variable from a pickled file. However, what I had done was:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">elements = <span style="color: #dc143c;">pickle</span>.<span style="color: black;">load</span><span style="color: black;">&#40;</span><span style="color: #008000;">open</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'file'</span>, <span style="color: #483d8b;">'rb'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Normally, this would be okay, however, due to the size of the files, and the fact I was doing this in a loop, over different files, is that there was a now opened multi-megabyte file floating around, that has not been closed or reallocated. Actually, several. I came home after two hours to find that almost all of my RAM and 70% of my swap space had been used. Thats 70% of 3.8 GB. Yeah, great job Zeroth.</p>
<p>The lesson here is, that what works well for a small loop, or small files, does not neccesarilly work well for large files or large loops. Always make sure you close every file you open, and if worst comes to worst, allocate memory by using the <code>del</code> keyword in Python. I&#8217;m using this, and there is very moderate memory growth, as compared to the quite massive almost 6 GB of memory the code was taking up before.</p>
<p>So the proper way to do this is:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">f=<span style="color: #008000;">open</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'file'</span>, <span style="color: #483d8b;">'rb'</span><span style="color: black;">&#41;</span>
elements = <span style="color: #dc143c;">pickle</span>.<span style="color: black;">load</span><span style="color: black;">&#40;</span>f<span style="color: black;">&#41;</span>
f.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">del</span> f</pre></div></div>

<p>I do need to make this clear. This fault was not due to Python, or any problems or bugs in it, but rather with my own sloppy code. Even the best of us make mistakes, and I&#8217;m definitely not the best of us.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.oddco.ca/zeroth/zblog/2008/06/17/memory-management-in-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cool Python Tricks part II</title>
		<link>http://www.oddco.ca/zeroth/zblog/2007/12/05/cool-python-tricks-part-ii/</link>
		<comments>http://www.oddco.ca/zeroth/zblog/2007/12/05/cool-python-tricks-part-ii/#comments</comments>
		<pubDate>Wed, 05 Dec 2007 15:10:04 +0000</pubDate>
		<dc:creator>Zeroth</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[python tricks]]></category>
		<category><![CDATA[list comprehension]]></category>

		<guid isPermaLink="false">http://oddco.ca/zerothsblog/2007/12/05/cool-python-tricks-part-ii/</guid>
		<description><![CDATA[A new installment in my ever-popular series. Todays installment will concern one of the best performance enhancing tricks in python: list comprehensions. Most beginning pythonistas will produce code like this: lst=&#91;&#93; for i in range&#40;0, 10&#41;: lst.append&#40;i**2&#41; &#160; Now, thats pretty okay. It runs&#8230; okay. It is the kind of code I would expect from [...]]]></description>
			<content:encoded><![CDATA[<p><meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" /><title></title><meta name="GENERATOR" content="OpenOffice.org 2.3  (Unix)" /></p>
<style type="text/css"> 	<!-- 		@page { size: 21.59cm 27.94cm; margin: 2cm } 		P { margin-bottom: 0.21cm } 	--> 	</style>
<p>A new installment in my ever-popular <a href="http://oddco.ca/zerothsblog/category/python-tricks/" title="Cool python tricks! Tricks that will make you a better Python Guru">series.</a></p>
<p>Todays installment will concern one of the best performance enhancing tricks in python: list comprehensions.</p>
<p style="margin-bottom: 0cm">Most beginning pythonistas will produce code like this:</p>
<p style="margin-bottom: 0cm">

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">lst=<span style="color: black;">&#91;</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> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>:
     lst.<span style="color: black;">append</span><span style="color: black;">&#40;</span>i<span style="color: #66cc66;">**</span><span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span></pre></div></div>

<p><span id="more-32"></span></p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">Now, thats pretty okay. It runs&#8230; okay. It is the kind of code I would expect from a newcomer to Python, however, one of Python&#8217;s weaknesses is its slower running speed. This, by the way, is a weakness for pretty much any interpreted language, like Java or Ruby.</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">Now, imagine you have a much larger data set to work with. On the order of thousands, hundreds of thousands. Processing all of it at Python speed will drag your program down.</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">But, you are in luck: there is a faster way.</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">Unfortunately, this faster method has its own set of issues, and the first and most obvious one, is legibility. Done wrong this technique can and will obscure the meaning of your program, and make it harder to maintain.</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">This technique is list comprehensions. The upper piece of code would be, in a list comprehension,</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">lst=<span style="color: black;">&#91;</span>i<span style="color: #66cc66;">**</span><span style="color: #ff4500;">2</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;">0</span>, <span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span></pre></div></div>

</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">This line of code runs in C speed, not Python speed. For a large dataset, this can be an improvement of 10-100 times faster!</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">Now, lets break it down: there are three parts to a list comprehension. The first portion is an expression. The second portion is a <em>for </em>clause. And the third portion is one or more <em>for</em> or <em>if </em>clauses.</p>
<p style="margin-bottom: 0cm">The first for clause in the list comprehension declares a variable, and the expression must do something with that variable.</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">Or, for those language lawyers:</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm"><a title="tok-test" name="tok-test"></a>test ::= <a href="http://docs.python.org/ref/Booleans.html#tok-or_test">or_test</a> | <a href="http://docs.python.org/ref/lambdas.html#tok-lambda_form">lambda_form</a></p>
<p style="margin-bottom: 0cm"><a title="tok-testlist" name="tok-testlist"></a>testlist ::= <a href="http://docs.python.org/ref/lists.html#tok-test">test</a> ( &#8220;,&#8221; <a href="http://docs.python.org/ref/lists.html#tok-test">test</a> )* [ "," ]</p>
<p style="margin-bottom: 0cm"><a title="tok-list_display" name="tok-list_display"></a>list_display ::= &#8220;[" [<a href="http://docs.python.org/ref/lists.html#tok-listmaker">listmaker</a>] &#8220;]&#8221;</p>
<p style="margin-bottom: 0cm"><a title="tok-listmaker" name="tok-listmaker"></a>listmaker ::= <a href="http://docs.python.org/ref/Booleans.html#tok-expression">expression</a> ( <a href="http://docs.python.org/ref/lists.html#tok-list_for">list_for</a> | ( &#8220;,&#8221; <a href="http://docs.python.org/ref/Booleans.html#tok-expression">expression</a> )* [","] )</p>
<p style="margin-bottom: 0cm"><a title="tok-list_iter" name="tok-list_iter"></a>list_iter ::= <a href="http://docs.python.org/ref/lists.html#tok-list_for">list_for</a> | <a href="http://docs.python.org/ref/lists.html#tok-list_if">list_if</a></p>
<p style="margin-bottom: 0cm"><a title="tok-list_for" name="tok-list_for"></a>list_for ::= &#8220;for&#8221; <a href="http://docs.python.org/ref/exprlists.html#tok-expression_list">expression_list</a> &#8220;in&#8221; <a href="http://docs.python.org/ref/lists.html#tok-testlist">testlist</a> [<a href="http://docs.python.org/ref/lists.html#tok-list_iter">list_iter</a>]</p>
<p style="margin-bottom: 0cm"><a title="tok-list_if" name="tok-list_if"></a>list_if ::= &#8220;if&#8221; <a href="http://docs.python.org/ref/lists.html#tok-test">test</a> [<a href="http://docs.python.org/ref/lists.html#tok-list_iter">list_iter</a>]</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">Basically, a list comprehension consists of:</p>
<p style="margin-bottom: 0cm">

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: black;">&#91;</span>expression using <span style="color: #483d8b;">'x'</span> variable <span style="color: #ff7700;font-weight:bold;">for</span> clause declaring <span style="color: #483d8b;">'x'</span> <span style="color: black;">&#40;</span>optionally: <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #483d8b;">'x'</span> meets some condition<span style="color: black;">&#41;</span><span style="color: black;">&#93;</span></pre></div></div>

</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">Again, one of the cardinal rules of optimization are that you only optimize when you know where the bottlenecks are. So, when you first code a for loop or list initialization, use the regular for loop. Then, after the program works, you can optimize it out to a list comprehension, and test the resulting speed.</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">This will, in most cases, make your program faster, and make you a Python guru. So, till next time, keep on hissing!</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
<p style="margin-bottom: 0cm">&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.oddco.ca/zeroth/zblog/2007/12/05/cool-python-tricks-part-ii/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cool Python Tricks part I</title>
		<link>http://www.oddco.ca/zeroth/zblog/2007/11/30/cool-python-tricks-part-i/</link>
		<comments>http://www.oddco.ca/zeroth/zblog/2007/11/30/cool-python-tricks-part-i/#comments</comments>
		<pubDate>Fri, 30 Nov 2007 03:25:27 +0000</pubDate>
		<dc:creator>Zeroth</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[python tricks]]></category>
		<category><![CDATA[borg design patterns]]></category>

		<guid isPermaLink="false">http://oddco.ca/zerothsblog/2007/11/30/cool-python-tricks-part-i/</guid>
		<description><![CDATA[I&#8217;ve spent almost five years programming as a hobby, and my first language was Python. Its still one of my favourites for many reasons; simplicity, power, rapid development, and its fun. Due to its nature, Python is very flexible and very versatile, and over the years, I&#8217;ve learned some very very cool and useful python [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve spent almost five years programming as a hobby, and my first language was Python. Its still one of my favourites for many reasons; simplicity, power, rapid development, and its fun.</p>
<p>Due to its nature, Python is very flexible and very versatile, and over the years, I&#8217;ve learned some very very cool and useful python idioms and tricks.</p>
<p>What I will show today is a Design Pattern that fits the ideology of Python well, and delivers a great amount of flexibility and usefulness. Its called the Borg Design Pattern.<span id="more-28"></span></p>
<p>I&#8217;m sure we&#8217;re all familiar with the Singleton design pattern. The Borg DP is almost precisely the opposite. Instead of one instantiated object, and just one, the Borg DP allows you to instantiate any number of the objects, and have them all share the exact same traits, methods, variables.<br />
(assume there is proper formatting for this function)<br />
<code><br />
1| class Borg:<br />
2| _share_state={}<br />
3|    def __init__(self, *args, **kwargs):<br />
4|        self.__dict__=self._shared_state<br />
</code></p>
<p>Here&#8217;s the beauty of the Borg DP: on any of the instantiated objects, if you modify a variable, <strong>all</strong> of the instantiated objects reflect that modification. Every single one of them. Hence the name, Borg Design Pattern.</p>
<p>The important line here is line two: &#8220;__dict__={}&#8221; before you declare any methods of variables. When you do this in Python, all instantiated classes have a reference to that single variable and object. And __dict__ is an internal dict of the class, that stores all methods and all  variables!</p>
<p>The power of this trick is such that, you can use it for many of the same places you once used a Singleton, but without needing to worry about references, thread safe access, even checking how many objects have been instantiated. It cleans up all associated code, and gives you the confidence to know exactly what is going on with the object.</p>
<p>And thats part one! Stay tuned for more Cool Python Tricks(tm), hopefully one a week!</p>
<p>EDIT: Fixed borg design pattern, small bug.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.oddco.ca/zeroth/zblog/2007/11/30/cool-python-tricks-part-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

