<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"> <channel><title>Pedro Kroger</title> <link>http://pedrokroger.com</link> <description>Because programming is fun</description> <lastBuildDate>Wed, 15 Feb 2012 16:09:06 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/pedrokroger" /><feedburner:info uri="pedrokroger" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><title>Harmonizing every scale with Python</title><link>http://feedproxy.google.com/~r/pedrokroger/~3/jCyrIY7VEaM/</link> <comments>http://pedrokroger.com/2011/09/harmonizing-every-scale-with-python/#comments</comments> <pubDate>Thu, 29 Sep 2011 17:37:44 +0000</pubDate> <dc:creator>Pedro Kroger</dc:creator> <category><![CDATA[python]]></category> <guid isPermaLink="false">http://pedrokroger.com/?p=458</guid> <description><![CDATA[I was advising some students the other day about harmonizing non-traditional scales and someone mentioned how it would be useful to have a list of harmonizations for every possible scale. I bragged that I could write a program in half-hour to accomplish it. Of course it took longer than that, but I quickly wrote a [...]]]></description> <content:encoded><![CDATA[<p>I was advising some students the other day about harmonizing non-traditional scales and someone mentioned how it would be useful to have a list of harmonizations for every possible scale. I bragged that I could write a program in half-hour to accomplish it. Of course it took longer than that, but I quickly wrote a small python program to generate harmonizations for every possible scale and used <a
href="lilypond.org/">LilyPond</a> to typeset them.</p><p>The harmonization for the major scale is pretty simple; you stack notes vertically following every other note in the scale:</p><p><a
href="http://pedrokroger.com/2011/09/harmonizing-every-scale-with-python/scale/" rel="attachment wp-att-474"><img
class="alignnone size-medium wp-image-474" title="scale" src="http://images.pedrokroger.net/wp-content/uploads/2011/09/scale-300x52.png" alt="" width="300" height="52" /></a></p><p>In modern music it&#8217;s fairly common to use non-traditional scales to generate new and interesting harmonies. For instance, in the example bellow I have a 7-note scale that is very different from the good ol&#8217; major scale. Right after the scale we have harmonizations for every 3, 4, and 5 notes of the scale. Also notice that we break the thing about having the interval in which we pick notes be the same of the horizontal notes (that is, having chords in thirds, fourths, and so on). This leads to very interesting harmonies.</p><p><img
class="alignnone" title="Non-traditional scale harmonization" src="http://genosmus.com/wp-content/uploads/2011/09/Escalas.png" alt="" width="705" height="167" /></p><p>By the way, this is one of the reasons I got into programming in the first place; to generate material to use in my <a
title="Compositions" href="http://pedrokroger.com/compositions/">compositions</a> (using Pascal back in the 90&#8242;s, if you must know).</p><p>So, in order to harmonize every scale we need to know how many scales exist and the answer will vary depending to whom you ask. In a way a scale is an ordered set of notes, so I used the 129 <a
href="http://en.wikipedia.org/wiki/Set_theory_(music)">pitch class sets</a> with cardinality greater than 5. <a
href="https://github.com/kroger/musiclib/blob/master/musiclib/pc_sets.py">Here</a> is a complete list of all pitch class sets. Some people will find that using <a
href="http://www.jaytomlin.com/music/settheory/help.html#primeform">prime forms</a> is too condensed and doesn&#8217;t take in account a bunch of scales, but it&#8217;ll do for the purpose of this post.</p><p>The code to generate the harmonizations is actually very simple (with the help of my in-progress <a
href="https://github.com/kroger/musiclib">python library</a>). We harmonize the first note of a scale with <tt>harmonize_first_note</tt> and use it in a list comprehension to harmonize every note of the scale. The helper function <tt>rotate_set</tt> will generate every rotation of a list.</p><pre class="brush:py">def harmonize_first_note(scale, interval, size):
    i = (interval - 1)
    indexes = [x % len(scale) for x in range(0, size * i, i)]
    return [scale[index] for index in indexes]
def harmonize_scale(scale, interval, size=3):
    scales = musiclib.rotate_set(sorted(scale))
    return [harmonize_first_note(scale, interval, size) for scale in scales]</pre><p>Here&#8217;s how we use it: A scale is defined as a list of integers (we are using <a
href="http://en.wikipedia.org/wiki/Pitch_class#Integer_notation">integer notation</a>). Let&#8217;s put the major scale in a variable:</p><pre class="brush:py">scale = [0, 2, 4, 5, 7, 9, 11]</pre><p>The result of <tt>harmonize_first_note</tt> will be, as expected, just the first chord (C major) as a list of integers:</p><pre class="brush:py">harmonize_first_note(scale, 3, 3)
&gt;&gt;&gt; [0, 4, 7]</pre><p>And the result of <tt>harmonize_scale</tt> will be a list with the harmonization of every chord in the scale. In the next example I&#8217;m using 4 as the chord size to generate tetrads:</p><pre class="brush:py">harmonize_scale(scale, 3, 4)
&gt;&gt;&gt; [[0, 4, 7, 11], [2, 5, 9, 0], [4, 7, 11, 2], [5, 9, 0, 4],
     [7, 11, 2, 5], [9, 0, 4, 7], [11, 2, 5, 9]]</pre><p>Finally, lets generate tetrads separated by fourths instead of thirds:</p><pre class="brush:py">harmonize_scale(scale, 4, 4)
&gt;&gt;&gt; [[0, 5, 11, 4], [2, 7, 0, 5], [4, 9, 2, 7], [5, 11, 4, 9],
     [7, 0, 5, 11], [9, 2, 7, 0], [11, 4, 9, 2]]</pre><p>The code to generate the LilyPond file is boring, so I won&#8217;t talk about it here. You can see it in the <a
href="https://github.com/kroger/scales/blob/master/scales.py#L32">repository</a>.</p><p>Generating harmonizations for every scale is interesting and all, but it start to get interesting when we can filter things. For instance, I may want to generate harmonizations for the scales that have more than 4 notes and have consecutive intervals greater than 1 semitone. This can be accomplished with <tt>filter_sets</tt>. This is how I&#8217;d express the previous example:</p><pre class="brush:py">filter_sets(lambda intervals, size: size &gt; 4 and 1 not in intervals)</pre><p>The function <tt>filter_sets</tt> accepts an anonymous function with a list of the consecutive intervals in a set and the size of a set as parameters. If the condition in the body of the anonymous function is met the set is returned:</p><pre class="brush:py">def filter_sets(condition):
    sets = {}
    for forte, pc_set in musiclib.PC_SETS.items():
        intervals = musiclib.intervals(pc_set)
        size = len(pc_set)
        if condition(intervals, size):
            sets[forte] = pc_set
    return sets</pre><p>This is an example of how high-order functions can be used to abstract code. Also, the built-in function <tt>all</tt> is very handy to chain conditions. Let&#8217;s say I want to get scales that have more than 4 notes and have only 1 consecutive halftone and 1 consecutive whole tone:</p><pre class="brush:py">filter_sets(lambda i, s: all([s &gt; 4, i.count(1) == 1,
                              i.count(2) == 1]))</pre><p>Since I want to filter scales by interval content, it makes sense to write a small function to help me. <tt>cond_interval_count</tt> abstracts the previous code:</p><pre class="brush:py">def cond_interval_count(count_list):
    return lambda i, s: all([i.count(interval) == count for
                             count, interval in count_list])</pre><p>So if I want the scales that have no consecutive halftones and only 1 consecutive whole tone I can write it as:</p><pre class="brush:py">cond = cond_interval_count(((0, 1), (1, 2)))
filter_sets(cond)</pre><p>There are a few things that can be improved:</p><ul><li>Use some pitch spelling algorithm, like <a
href="http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.12.8569">(Meredith, 2003)</a> so we won&#8217;t have chords like C, D#, G</li><li>Have better functions for filtering. The function I&#8217;m using looks for consecutive intervals but it would be better to search for every interval in the Pitch Class Set.</li><li>Handle octaves better in the LilyPond generation. Some notes would be better on a different octave:<br
/> <a
href="http://genosmus.com/wp-content/uploads/2011/09/Oitava-errada.png"><img
title="Oitava errada" src="http://genosmus.com/wp-content/uploads/2011/09/Oitava-errada.png" alt="" width="62" height="79" /></a></li></ul><p>This post only scratches the surface of all things we can do. For anything more complicated than that I&#8217;d use <a
title="music21" href="http://mit.edu/music21/">music21</a>, a nice and professional Python library for computer-aided musicology. But it&#8217;s interesting too see how far we can go with a few dozen lines of pure Python code and the use of nice abstractions.</p><p>If you have an interest in this kind of thing, there are lots of <a
href="http://wiki.python.org/moin/PythonInMusic">Python packages</a> for music programming and <a
href="http://www.amazon.com/Notes-Metalevel-Introduction-Computer-Composition/dp/9026519753">Notes from the Metalevel: An Introduction to Computer Composition</a> is a nice book about the topic (but it uses Scheme, not Python for the code).</p><p><a
class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpedrokroger.com%2F2011%2F09%2Fharmonizing-every-scale-with-python%2F&amp;title=Harmonizing%20every%20scale%20with%20Python" id="wpa2a_2"><img
src="http://pedrokroger.com/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p><img src="http://feeds.feedburner.com/~r/pedrokroger/~4/jCyrIY7VEaM" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pedrokroger.com/2011/09/harmonizing-every-scale-with-python/feed/</wfw:commentRss> <slash:comments>1</slash:comments> <feedburner:origLink>http://pedrokroger.com/2011/09/harmonizing-every-scale-with-python/</feedburner:origLink></item> <item><title>Printing python code with LaTeX</title><link>http://feedproxy.google.com/~r/pedrokroger/~3/WrsPGcOA8ow/</link> <comments>http://pedrokroger.com/2011/04/printing-python-code-with-latex/#comments</comments> <pubDate>Mon, 11 Apr 2011 01:35:15 +0000</pubDate> <dc:creator>Pedro Kroger</dc:creator> <category><![CDATA[latex]]></category> <category><![CDATA[python]]></category> <guid isPermaLink="false">http://pedrokroger.com/?p=434</guid> <description><![CDATA[Call me old fashioned but I like to review my code by printing it. Yes. Printing. On dead tree. The advantage of reviewing code on paper instead of the monitor is that I can give my eyes a break and I can annotate more freely, connect things with arrows, draw boxes, etc. I don&#8217;t print [...]]]></description> <content:encoded><![CDATA[<p>Call me old fashioned but I like to review my code by printing it. Yes. Printing. On dead tree.</p><p>The advantage of reviewing code on paper instead of the monitor is that I can give my eyes a break and I can annotate more freely, connect things with arrows, draw boxes, etc. I don&#8217;t print my code everyday, after all this is not the 80&#8242;s, but I like to print the code when I feel it could benefit from some refactoring and re-structuring and my brain could benefit from same change in the medium and even location (I can grab the printouts and go to a park or cafe).</p><p>The best way I found to print code is by using the LaTaX <a
title="LaTeX Listings package" href="http://www.ctan.org/tex-archive/macros/latex/contrib/listings/">listings</a> package (it should be included in any modern LaTeX distribution). This package is intended to include code snippets in papers and books, but it works to generate code listings as well.</p><p>These are the options I have in my LaTeX document header:</p><pre>\documentclass[10pt]{article}
\usepackage[T1]{fontenc}
\usepackage[scaled]{beramono}
\renewcommand*\familydefault{\ttdefault}
\usepackage{listings}</pre><p>&nbsp;</p><p>The <a
title="Beramono package" href="http://www.tug.dk/FontCatalogue/beramono/">beramono</a> package is a version of Bitstream Vera Mono modified to work with TeX. Without it we&#8217;ll get the default LaTeX mono font:</p><p><img
class="s3-img" style="border: 0px initial initial;" src="http://images.pedrokroger.net/code-ugly.png" border="0" alt="code-ugly.png" width="402" height="123" /></p><p>But I like Bitstream Vera better (it looks even betten on paper):</p><p><img
class="s3-img" style="border: 0px initial initial;" src="http://images.pedrokroger.net/code-pretty.png" border="0" alt="code-pretty.png" width="309" height="113" /></p><p>Listings has support for Python out-of-the-box and has lots of options and features (check the <a
title="Listings manual" href="http://mirrors.ctan.org/macros/latex/contrib/listings/listings.pdf">manual</a> to see what listings can do). These are the options I like to customize:</p><pre>\lstset{
  language=Python,
  showstringspaces=false,
  formfeed=\newpage,
  tabsize=4,
  commentstyle=\itshape,
  basicstyle=\ttfamily,
  morekeywords={models, lambda, forms}
}</pre><p>Options like <tt>tabsize</tt> and <tt>showstringspace</tt> are self-explanatory. The option <tt>formfeed=\newpage</tt> will replace the formfeed character by the LaTeX command <tt>\newpage</tt>, creating a new page at that point. Sometimes I put some line feed characters in my code so I can do things like <a
title="Narrow to a page" href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Narrowing.html">narrowing to a page</a> in Emacs. Emacs shows line feed characters as ^L, as you can see here:</p><p><img
class="s3-img" src="http://images.pedrokroger.net/emacs-formfeed.png" border="0" alt="emacs-formfeed.png" /></p><p>The option <tt>morekeywords</tt> will add the keywords in the list of keywords recognized by Listings. In my example I added <tt>lambda</tt>, <tt>models</tt> and <tt>forms</tt> (I&#8217;ve been working a lot with Django lately), so these keywords will be pretty-printed.</p><p>Finally, I use the command <tt>\lstinputlisting</tt> to include a source code file in the LaTeX file (instead of having to type the whole thing in the LaTeX file). I like to separate each section by a horizontal line and add some space at the end. I define a command to abstract this:</p><pre>\newcommand{\code}[2]{
  \hrulefill
  \subsection*{#1}
  \lstinputlisting{#2}
  \vspace{2em}
}</pre><p>So in the end this is how I insert a Python file:</p><pre>\code{Models}{../testapp/models.py}</pre><p>&nbsp;</p><p>And this is the result:<br
/> <img
class="s3-img" style="border: 0px initial initial;" src="http://images.pedrokroger.net/listings-model.png" border="0" alt="listings-model.png" width="550" height="337" /></p><p>Pretty neat huh? I believe that reviewing my code on paper has save me hours of work and I find listings to be a very good option to print source code. I added a full LaTeX template <a
title="latex template" href="http://pastebin.com/RiGKvz0y">here</a>.</p><p>Do you print your source code? If so, what tool do you use? Let me know in the comments.</p><p><a
class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpedrokroger.com%2F2011%2F04%2Fprinting-python-code-with-latex%2F&amp;title=Printing%20python%20code%20with%20LaTeX" id="wpa2a_4"><img
src="http://pedrokroger.com/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p><img src="http://feeds.feedburner.com/~r/pedrokroger/~4/WrsPGcOA8ow" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pedrokroger.com/2011/04/printing-python-code-with-latex/feed/</wfw:commentRss> <slash:comments>7</slash:comments> <feedburner:origLink>http://pedrokroger.com/2011/04/printing-python-code-with-latex/</feedburner:origLink></item> <item><title>Notes from The 4-hour Workweek</title><link>http://feedproxy.google.com/~r/pedrokroger/~3/UtnWTNZvcak/</link> <comments>http://pedrokroger.com/2010/10/notes-from-the-4-hour-workweek/#comments</comments> <pubDate>Fri, 08 Oct 2010 19:26:09 +0000</pubDate> <dc:creator>Pedro Kroger</dc:creator> <category><![CDATA[books]]></category> <category><![CDATA[lifestyle]]></category> <guid isPermaLink="false">http://pedrokroger.net/blog/?p=392</guid> <description><![CDATA[The 4-Hour Workweek is a great book with lots of good advice. I had some notes about the first edition gathering dust in my hard drive and I decided to post them here. They probably don&#8217;t make a lot of sense if you haven&#8217;t read the book, but I think they are good for a [...]]]></description> <content:encoded><![CDATA[<p><a
title="the 4-hour workweek" href="http://www.amazon.com/4-Hour-Workweek-Escape-Live-Anywhere/dp/0307353133">The 4-Hour Workweek</a> is a great book with lots of good advice. I had some notes about the first edition gathering dust in my hard drive and I decided to post them here. They probably don&#8217;t make a lot of sense if you haven&#8217;t read the book, but I think they are good for a quick review. There are also a set of notes <a
title="more notes" href="http://www.randomwok.com/raw-notes-book-reviews/raw-notes-the-4-hour-workweek/">here</a>.</p><h2>Definition</h2><p>New Rich (NR) to be the owner, not the boss nor the emplayee. &#8220;To own the trains<br
/> and have someone else ensure they run on time.&#8221; (p. 23)</p><p>NR examples:</p><ol><li>employee who gets 90% of work done in 10% of time and use the remaining time to do whatever he likes (e.g. road trips)</li><li>student who has an online video rental service and makes $5000 a month working 2 hours a week.</li></ol><p>Being a NR is to challenge the <em>status quo</em> but is not to be stupid</p><ol><li>Retirement is a worst-case scenario insurance: and it&#8217;s difficult to retire and mantain the same standard of living</li><li>Interest and energy are cyclical: the best is to have mini-retirements distributed throughout life. The author aims for 1 month overseas for each 2 months of work.</li><li>Less is not laziness: The point is to do less meaningless work and produce more meaningful result. 80/20 rule.</li><li>The timing is never right</li><li>Ask for forgiveness, not permission</li><li>Emphasize strengths, don&#8217;t fix weaknesses: &#8221;Focus on better use of your best weapons instead of constant repair&#8221; (p. 34)</li><li>Things in excess become their opposite: Lifestyle design is not intended to increase idle time, but &#8220;the positive use of free time&#8221;. (p. 35)</li><li>Money alone is not the solution</li><li>Relative income is more important than absolute income: The ratio between money earned and time worked is what define how a person makes. NR make $5000 per hour. (They may earn 10,000 a month and only work 2 hours a month).</li><li>Distress is bad, eustress is good</li></ol><p>Conquer fear by defining it. What&#8217;s the worst it can happen from a 1-10 scale?</p><ol><li>Define your nightmare</li><li>What steps to repair te damage (even if temporarily)</li><li>What are the positive outcomes?</li><li>If you were fired today what would you do to get things under financial control?</li><li>What are you putting off out of fear? &#8221;What we fear doing most is usually what we most need to do&#8221; (p. 46)</li><li>What is costing you to postpone action?</li><li>What are you waiting for?</li></ol><p>Doing the unrealistic is easier than doing the realistic.</p><h3>Planning the dreams</h3><ol><li>Create 2 timelines (6 and 12 months) and list 5 things you dream of having, being, and doing considering you couldn&#8217;t fail.</li><li>If you don&#8217;t know what to think in 1., consider what you&#8217;d do if you had $100 million in the bank and what make you excited to wake up in the morning.</li><li>Convert each &#8220;being&#8221; into a &#8220;doing&#8221;. For example:<br
/> Great cook -&gt; make Christmas dinner without help<br
/> Fluent in Chinese -&gt; have a five-minute conversation with a Chinese co-worker</li><li>Highlight (star) the 4 most exciting and important dreams from all columns.</li><li>Determine the cost of these dreams and calculate your TMI (target monthly income) for both timelines. Use the tools on the website.</li><li>Determine 3 steps for each of the 4 dreams in the 6-month timeline and take the first step now.</li></ol><p>If someone has done it, ask for advice.</p><h2>Elimination</h2><p>Apply Pareto&#8217;s law and beware of Parkinson&#8217;s law.</p><ol><li>If I had an heart attack and had to work 2 hours per day, what would I do?</li><li>If I had a 2nd heart attack and had to work 2 hours per *week*, what would I do?</li><li>What time-consuming activities can I remove?</li><li>Learn to ask &#8220;If this is the only thing I accomplish today, will I be satified with my day?&#8221;</li><li>Do not multitask.</li><li>Go on a low-information diet.</li><li>Check email twice a day (and latter once)</li></ol><h2>Automation</h2><ul><li>Get a personal assistant</li><li>Eliminate before you delegate</li><li>Learn to delegate</li><li>Each delegated task must be both time-consuming and well-defined</li><li>Request an especific kind of assistant (e.g. &#8220;with excelent English&#8221;)</li><li>Request an update after a few hours</li><li>Break in small milestones</li><li>Example: &#8220;Please reply and confirm what you will plan to do to complet this task&#8221;</li><li>Get an assistent even if you don&#8217;t need one (to train how to command)</li><li>Think &#8220;what tasks can I delegate do a VA?&#8221;</li></ul><h3>Income autopilot</h3><p>He uses <a
title="Prosoundeffects" href="http://prosoundeffects.com">Prosoundeffects</a> as an example.</p><p>The product can&#8217;t take more than $500 to test, has to lend to automation within 4 weeks and can&#8217;t require more than 1 day per week of management.</p><ol><li>pick an affordable and reachable nich market</li><li>brainstorm products: explain the product in one sencence (e.g. ipod: &#8220;1000 songs in your pocket&#8221;)</li><li>price should be between $50&#8211;200: higher prices mean fewer units, less costumers, and lower-maintenance costomers.</li><li>resell a product</li><li>License a product</li><li>Create a product: Information is difficult to replicate (legally), e.g. training DVD for security systems.</li><li>how to become a top expert</li></ol><ul><li>join 2 or 3 trade organizations</li><li>read the 3 top-selling books</li><li>give one free 1-to-3 hour seminar at a well known university (and/or companies)</li><li>write 1 or 2 articles in a trade magazine</li><li>join profnet</li></ul><p><span
style="font-size: 18px; color: #000000; line-height: 27px;">Testing the muse</span></p><p>micro test products with Google adsense</p><ul><li>find competition to determine why my product is better</li><li>test advertisement with ebay auction (cancel auction on the last minute)</li><li>set-up google campaign</li></ul><ol><li>Market selection</li><li>Product brainstorm</li><li>Micro-testing</li><li>Roll out and automation</li></ol><h3>Management by absence</h3><ol><li>1. 0-50 total units of product shipped: do it all yourself</li><li>more than 10 units shipped per week<br
/> add faq to website and answer questions<br
/> find fulfillment services or &#8220;mailing services&#8221; or mfsanet.org</li><li>more than 20 units per week<br
/> outsource<br
/> set up merchant account</li><li>have fewer options</li></ol><h2>Liberation</h2><p>How to negotiate to work remotely.</p><p><a
class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpedrokroger.com%2F2010%2F10%2Fnotes-from-the-4-hour-workweek%2F&amp;title=Notes%20from%20The%204-hour%20Workweek" id="wpa2a_6"><img
src="http://pedrokroger.com/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p><img src="http://feeds.feedburner.com/~r/pedrokroger/~4/UtnWTNZvcak" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pedrokroger.com/2010/10/notes-from-the-4-hour-workweek/feed/</wfw:commentRss> <slash:comments>1</slash:comments> <feedburner:origLink>http://pedrokroger.com/2010/10/notes-from-the-4-hour-workweek/</feedburner:origLink></item> <item><title>SICP in Python: 1.1 The Elements of Programming</title><link>http://feedproxy.google.com/~r/pedrokroger/~3/H1WkCsjypQM/</link> <comments>http://pedrokroger.com/2010/09/sicp-in-python-1-1-the-elements-of-programming/#comments</comments> <pubDate>Wed, 01 Sep 2010 03:00:26 +0000</pubDate> <dc:creator>Pedro Kroger</dc:creator> <category><![CDATA[python]]></category> <category><![CDATA[sicp]]></category> <guid isPermaLink="false">http://pedrokroger.net/blog/?p=282</guid> <description><![CDATA[[I'm writing a series of posts about SICP in Python. You can read more about the reasoning in the introductory post.] The first chapter is about building abstractions with functions. I think it&#8217;s remarkable that a book for beginners (pretty smart beginners, but still) introduces assignment only in the third chapter (on page 220). I really [...]]]></description> <content:encoded><![CDATA[<p><em> </em>[I'm writing a series of posts about SICP in Python. You can read more about the reasoning in the <a
title="introduction SICP in python" href="http://pedrokroger.net/blog/2010/08/sicp-in-python/">introductory post</a>.]</p><p>The first chapter is about building abstractions with functions. I think it&#8217;s remarkable that a book for beginners (pretty smart beginners, but still) introduces assignment only in the third chapter (on page 220). I really think this is the way to start a programming course. Probably all students know about mathematical functions and with functions we can talk about things like bound variables, scope, abstraction, composition, and recursion.</p><p>A powerful language needs to have the following things to allow the combination of simple ideas to form complex ideas:</p><ul><li><strong>primitive expressions:</strong> the simplest entities in a language. Things like numbers and arithmetic operations and functions.</li><li><strong>means of combination:</strong> &#8220;by which compound elements are built from simpler ones&#8221;. Nesting combinations, such as <tt>square(2 * square(3 + 7))</tt> are simple means of combination.</li><li><strong>means of abstraction:</strong> &#8220;by which compound elements can be named and manipulated as units&#8221;.</li></ul><p><span
style="font-size: 15.8333px;"><strong>def</strong> is the simplest mean of abstraction. The following code creates a function and associates it with a name:</span></p><pre class="brush:py">def square(x):
    return x * x</pre><p>It&#8217;s important to make the distinction of the act of creating a function and naming it. We can create a function without a name (an anonymous function) with <em>lambda</em>:</p><pre class="brush:py">lambda x: x * x</pre><p>And we can assign it to a variable, giving it a name:</p><pre class="brush:py">square2 = lambda x: x * x</pre><p>And, in fact, we can see (with the help of the <a
title="python disassembler module" href="http://docs.python.org/library/dis.html">bytecode disassembler module</a>) that Python will generate the same bytecode for both <em>square</em> and<em> square2</em>:</p><pre class="brush:py">&gt;&gt;&gt; import dis
&gt;&gt;&gt; dis.dis(square)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                0 (x)
              6 BINARY_MULTIPLY
              7 RETURN_VALUE
&gt;&gt;&gt; dis.dis(square2)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                0 (x)
              6 BINARY_MULTIPLY
              7 RETURN_VALUE</pre><p>Having defined <em>square, </em>we can use it in combinations:</p><pre class="brush:py">square(2 + 5)
square(square(7 + square (3)))</pre><p>And, naturally, we can use <em>square</em> as a building block:</p><pre class="brush:py">def sum_of_squares(x, y):
    return square(x) + square(y)
sum_of_squares(3, 4)
def f(a):
    return sum_of_squares(a + 1, a * 2)</pre><p>The association between names and values, such as the name of a function, is saved in a place called the <em>environment</em>. Chapter 3 will talk about the environment in greater detail.</p><h2>Applicative order and normal order</h2><p>To evaluate combinations we follow a recursive rule (quoted verbatim):</p><ol><li><span
style="font-size: 15.8333px;">Evaluate the subexpressions of the combination.</span></li><li><span
style="font-size: 15.8333px;">Apply the procedure that is the value of the leftmost subexpression (the operator) to the arguments that are the values of the other subexpressions (the operands).</span></li></ol><p>The <a
title="the substitution module" href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_sec_1.1.5">substitution model</a> is a simple model to help us understand what happens during evaluation. To evaluate procedures we have the following rule:</p><blockquote><p>To apply a compound procedure to arguments, evaluate the body of the procedure with each formal parameter replaced by the corresponding argument.</p></blockquote><p>Keep in mind that &#8220;the purpose of the substitution is to help us think about procedure application, not to provide a description of how the interpreter really works&#8221; and SICP presents &#8220;a sequence of increasingly elaborate models of how interpreters work, culminating with a complete implementation of an interpreter and compiler in chapter 5&#8243;.</p><p><span
style="font-size: 15.8333px;">In the example below we can see two ways to evaluate the function <em>f</em> we defined previously. The function <em>f</em> is defined in terms of <em>sum_of_squares</em>, which is defined in terms of <em>square</em>, which is defined as the multiplication of a number by itself. In the evaluation method on the left, an expression such as 5+1 is evaluated and applied immediately. This method of evaluation is known as <a
title="applicative order evaluation" href="http://en.wikipedia.org/wiki/Evaluation_strategy#Applicative_order">applicative order evaluation</a> (a kind of <a
title="strict evaluation" href="http://en.wikipedia.org/wiki/Strict_evaluation">strict evaluation</a>, used in most programming languages, inclusive Python and Scheme). The evaluation method on the right only evaluates an expression when needed. It&#8217;ll fully expand all function calls first, and then evaluate what&#8217;s left. This is known as <em>normal order evaluation.</em> Compare the result of both methods in line 5:</span></p><pre class="brush:py"># applicative order        normal order
f(5)                       f(5)
sum_of_squares(5+1, 5*2)   sum_of_squares(5+1, 5*2)
sum_of_squares(6, 10)      square(5+1) + square(5*2)
square(6) + square(10)     ((5+1) * (5+1)) + ((5*2) * (5*2))
(6 * 6) + (10 * 10)        (6 * 6) + (10 * 10)
36 + 100                   36 + 100
136                        136</pre><p>Of course both methods yield the same answer, but this will not always be the case, as we&#8217;ll see latter in this post (exercise 1.5) and in this series.</p><h2>Conditional expressions and predicates</h2><p>The main point of this sub-section is to show how to write conditional expressions in Scheme by implementing a function named  <em>abs</em> to calculate the absolute value of a number. Since <em>abs</em> is a built-in function in Python,  I&#8217;ll use <em>myabs</em> (it&#8217;s pretty hard not to think about cheesy late-night infomercials with a function named like this <img
src='http://pedrokroger.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> ). The first implementation follows the mathematical definition and uses multiple predicates:</p><pre class="brush:py">def myabs(x):
    if x &gt; 0:
        return x
    elif x == 0:
        return x
    elif x &lt; 0:
        return x</pre><p>This is unnecessarily long and can be shortened as:</p><pre class="brush:py">def myabs(x):
    if x &lt; 0:
        return -x
    else:
        return x</pre><p>And it can be even shorter by using the ternary operator (new in Python 2.5):</p><pre class="brush:py">def myabs(x):
    return -x if x &lt; 0 else x</pre><p>This sub-section also shows logical operators such as <em>and</em>, <em>or</em>, and <em>not</em>. For instance, in Scheme the expression 5 &lt; x &lt; 10 would be written as <tt>(and (&gt; x 5) (&lt; x 10))</tt> but the same thing in Python is just <tt>5 &lt; x &lt; 10.</tt> Pretty cool, huh?</p><h3>Exercise 1.4</h3><p>This exercise asks the reader to describe the behavior of the following procedure. I&#8217;ll use the original Scheme code, then I&#8217;ll show the equivalent in Python.</p><pre>(define (a-plus-abs-b a b)
  ((if (&gt; b 0) + -) a b))</pre><p>This code may look weird at first (and I&#8217;m not talking about the parenthesis <img
src='http://pedrokroger.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> ), but we can just apply the substitution model to understand how it works. Let&#8217;s copy the function&#8217;s body:</p><pre>((if (&gt; b 0) + -) a b)</pre><p>If <em>b</em> is greater than 0, the conditional expression will return the <em>+</em> (addition) function, otherwise it&#8217;ll return the &#8211; (subtraction) function. In Scheme + and &#8211; are functions, just like <em>sqrt. </em>Let&#8217;s suppose that <em>b</em> is greater than 0 and the conditional expression will return +. We substitute + for the conditional expression:</p><pre>(+ a b)</pre><p>The resulting expression is just the sum of <em>a</em> and <em>b</em>. This kind of thing is possible because in Scheme functions are <a
title="first-class functions" href="http://en.wikipedia.org/wiki/First-class_function">first-class</a>; we can create them at runtime, pass them as arguments to other functions, and return them as values.</p><p>Functions are also first-class in Python, but + and &#8211; are not functions. We can access Python&#8217;s basic operators with the <em>operator</em> module. For instance, <em>operator.add(2, 2)</em> is equivalent to the expression <em>2 + 2</em>. So, we can write the Scheme code above in Python as:</p><pre class="brush:py">from operator import add, sub
def a_plus_abs_b(a, b):
    return (add if b &gt; 0 else sub)(a, b)</pre><h3>Exercise 1.5</h3><p>This exercise asks the reader to describe the behavior of the following code if the interpreter uses applicative order evaluation and normal order evaluation.</p><pre class="brush:py">def p():
    return p()
def test(x, y):
    return 0 if x == 0 else y
test(0, p())</pre><p>In applicative order evaluation, the interpreter will enter in an infinite loop, regardless of the value of <em>test</em>&#8216;s first argument, because both operands will be evaluated before the function is called (line 7). With normal order evaluation, the interpreter will evaluate only what is necessary, so if the first argument of <em>test</em> is 0, it&#8217;ll return 0 because the second argument will not be evaluated.</p><h2>Example: square roots by Newton&#8217;s method</h2><p>One way to calculate square roots is by using Newton&#8217;s method of successive approximations. We start with a guess <em>g</em> for the square root of a number <em>x</em> and calculate a better guess by averaging <em>g</em> with <img
src='http://s.wordpress.com/latex.php?latex=x%2Fg&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x/g' title='x/g' class='latex' />, or:</p><p><span
style="font-size: 15.8333px;"><img
src='http://s.wordpress.com/latex.php?latex=G%3D%5Cfrac%7Bg%2Bx%2Fg%7D%7B2%7D&#038;bg=ffffff&#038;fg=000000&#038;s=2' alt='G=\frac{g+x/g}{2}' title='G=\frac{g+x/g}{2}' class='latex' /></span></p><p><span
style="line-height: 23px;">The following procedure tests if the guess we have is good enough for the number <em>x</em> (the radicand) we want to compute the square root. If not it&#8217;ll keep trying to improve the guess until it&#8217;s good enough:</span></p><pre class="brush:py">def sqrt_iter(guess, x):
    if is_good_enough(guess, x):
        return guess
    else:
        return sqrt_iter(improve(guess, x), x)</pre><p>To improve a guess we average it by the number <em>x</em> divided by the guess:</p><pre class="brush:py">def improve(guess, x):
    return average(guess, x/guess)</pre><p>Average is easy enough to define:</p><pre class="brush:py">def average(x, y):
    return (x + y)/2</pre><p>Of course, we need to define <em>is_good_enough</em>. A basic test is to see if the square of the guess minus the original number <em>x</em> is smaller than some threshold (we use 0.001). This is not a good test for very small and large numbers (see exercise 1.7 in the book) but will do for a first try:</p><pre class="brush:py">def is_good_enough(guess, x):
    return abs(square(guess) - x) &lt; 0.001</pre><p>Finally, we need to start at some point. We begin with 1.0 as a guess:</p><pre class="brush:py">def sqrt(x):
    return sqrt_iter(1.0, x)</pre><h2>Procedures as black-box abstractions</h2><p>One problem with our implementation of <em>sqrt</em> is that functions like <em>is_good_enough</em>, <em>sqrt_iter</em>, and <em>improve</em> are cluttering the global namespace. It&#8217;s very important to decompose a problem in sub-parts like we did, were each function does only one thing, but it&#8217;s also important to be able to group things that are not going to be used in other contexts (like <em>improve</em> and <em>sqrt_iter</em>). One solution is to nest the procedures in one <em>block structure</em>:</p><pre class="brush:py">def sqrt(x):
    def is_good_enough(guess, x):
        return abs(square(guess) - x) &lt; 0.001
    def improve(guess, x):
        return average(guess, x/guess)
    def sqrt_iter(guess, x):
        if is_good_enough(guess, x):
            return guess
        else:
            return sqrt_iter(improve(guess, x), x)
    return sqrt_iter(1.0, x)</pre><p>Now the functions <em>sqrt_iter</em>, <em>is_good_enough</em>, and <em>improve</em> are internal to <em>sqrt </em>and are not exposed to other programmers.</p><p>But there&#8217;s something else. <span
style="font-size: 15.8333px;">The variable <em>x</em> is bound in the scope of <em>sqrt</em> and since <em>improve</em>, <em>is_good_enough</em>, and <em>sqrt_iter</em> are in the scope of <em>sqrt</em> we don&#8217;t need to pass <em>x</em> explicitly as as argument to these functions. We can rewrite the code to make <em>x</em> a free variable inside these functions. In this case the interpreter will get the value of <em>x</em> from the enclosing scope<em>.</em> This is an example of <a
title="lexical scoping" href="http://en.wikipedia.org/wiki/Scope_(programming)#Lexical_scoping">lexical scoping</a>:</span></p><pre class="brush:py">def sqrt(x):
    def is_good_enough(guess):
        return abs(square(guess) - x) &lt; 0.001
    def improve(guess):
        return average(guess, x/guess)
    def sqrt_iter(guess):
        if is_good_enough(guess):
            return guess
        else:
            return sqrt_iter(improve(guess))
    return sqrt_iter(1.0)</pre><h2>Summary</h2><p>In the first section of SICP the authors introduce <span
style="font-size: 15.8333px;">the notion of the environment and lexical scoping (both will be explored in more detail latter in the book), </span><span
style="font-size: 15.8333px;">evaluation methods, and, above all, functional abstraction. I think this is a pretty sophisticated introduction for beginners and shows why SICP is considered one of the classics of computer science.</span></p><p><span
style="font-size: 15.8333px;">The notes for section 1.2 will come soon. Meanwhile, feel free to post suggestions and questions in the comments.</span></p><p><a
class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpedrokroger.com%2F2010%2F09%2Fsicp-in-python-1-1-the-elements-of-programming%2F&amp;title=SICP%20in%20Python%3A%201.1%20The%20Elements%20of%20Programming" id="wpa2a_8"><img
src="http://pedrokroger.com/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p><img src="http://feeds.feedburner.com/~r/pedrokroger/~4/H1WkCsjypQM" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pedrokroger.com/2010/09/sicp-in-python-1-1-the-elements-of-programming/feed/</wfw:commentRss> <slash:comments>4</slash:comments> <feedburner:origLink>http://pedrokroger.com/2010/09/sicp-in-python-1-1-the-elements-of-programming/</feedburner:origLink></item> <item><title>SICP in Python</title><link>http://feedproxy.google.com/~r/pedrokroger/~3/cB99BadizDI/</link> <comments>http://pedrokroger.com/2010/08/sicp-in-python/#comments</comments> <pubDate>Tue, 31 Aug 2010 18:55:59 +0000</pubDate> <dc:creator>Pedro Kroger</dc:creator> <category><![CDATA[python]]></category> <category><![CDATA[sicp]]></category> <guid isPermaLink="false">http://pedrokroger.net/blog/?p=274</guid> <description><![CDATA[Structure and Interpretation of Computer Programs is considered one of the great computer science books. Some  claim it will make you a better programmer. I'll post how the ideas in SICP will translate to Python.]]></description> <content:encoded><![CDATA[<p><em>Structure and Interpretation of Computer Programs</em> (a.k.a SICP, or &#8220;The Wizard Book&#8221;) is considered one of the <a
href="http://www.amazon.com/review/R3G05B1TQ5XGZP/ref=cm_cr_rdp_perm">great computer science books</a>. <a
href="http://programming-musings.org/2007/01/31/a-scheme-bookshelf/">Some people</a> claim it will make you a <a
href="http://lispy.wordpress.com/2007/10/13/how-studying-sicp-made-me-a-better-programmer/">better programmer</a>. It was the entry-level computer science subject at MIT and it&#8217;s still used in universities like Berkeley. One of the great things about SICP is that it focus on computational processes and ideas, instead of just teaching syntax. We can find more about the book&#8217;s goals in the <a
title="preface SICP" href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-7.html">Preface to the First Edition</a>:</p><blockquote><p>Our design of this introductory computer-science subject reflects two major concerns. First, we want to establish the idea that a computer language is not just a way of getting a computer to perform operations but rather that it is a novel formal medium for expressing ideas about methodology. Thus, <strong>programs must be written for people to read, and only incidentally for machines to execute</strong>. Second, we believe that the essential material to be addressed by a subject at this level is not the syntax of particular programming-language constructs, nor clever algorithms for computing particular functions efficiently, nor even the mathematical analysis of algorithms and the foundations of computing, but rather the techniques used to control the intellectual complexity of large software systems. <strong>Our goal is that students who complete this subject should have a good feel for the elements of style and the aesthetics of programming</strong>.</p></blockquote><p>The emphasis in bold is mine to show a couple of my favorite quotes (my favorite quote of all times must be Alan Perlis&#8217; &#8220;Syntactic sugar causes cancer of the semicolon&#8221;, but I digress).</p><p>The whole book is <a
title="SICP html book" href="http://mitpress.mit.edu/sicp/full-text/book/book.html">available for free</a> and the book&#8217;s page at MIT has lots of <a
title="SICP website" href="http://mitpress.mit.edu/sicp/">extra material</a>. Also, there are some highly recommended <a
title="SICP video lectures" href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/">video lectures</a> by the authors of the book.</p><p>SICP uses the Lisp dialect <a
title="scheme" href="http://en.wikipedia.org/wiki/Scheme_(programming_language)">scheme</a>, but since SICP concentrates on <em>programming ideas</em> rather than languages, there are some efforts to translate the code in the book to <a
title="SICP in other languages" href="http://www.codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages">other programming languages</a>. I think this is a good thing, because even if scheme is a beautiful language (it really is) and I think everyone should learn it, it&#8217;s good to see how the ideas presented in SICP can be translated to other languages.</p><p>I have read a good chunck of SICP and watched most video lectures before, but I didn&#8217;t do the exercises. Now, I want to read it again and do as many exercises as I can. Since I&#8217;ve been programming a lot in Python these days, I am curious to see how the ideas in SICP will translate to Python. So, my plan is to read the book and do the exercises using Python instead of Scheme. There are good <a
title="sicp notes" href="http://eli.thegreenplace.net/category/programming/lisp/sicp/">notes</a> and <a
href="http://www.kendyck.com/solutions-to-sicp/">solutions</a> for the exercises on the web and I may consult those as needed (giving fully credit, of course).</p><p>I&#8217;ll post my notes with the (Python) code. I&#8217;ll try to capture the essence of each section, instead of trying to post every single thing and exercise, but we&#8217;ll see how it works. I hope this will be a good resource for the Python community. Let me know in the comments what you think.</p><p><span
style="font-size: 15.9722px;">Why don&#8217;t you go ahead and read the <a
title="section 1.1" href="http://pedrokroger.net/blog/2010/08/sicp-in-python-1-1-the-elements-of-programming/">post about section 1.1</a>?</span></p> <img src="http://feeds.feedburner.com/~r/pedrokroger/~4/cB99BadizDI" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pedrokroger.com/2010/08/sicp-in-python/feed/</wfw:commentRss> <slash:comments>1</slash:comments> <feedburner:origLink>http://pedrokroger.com/2010/08/sicp-in-python/</feedburner:origLink></item> <item><title>The Python Quick Reference</title><link>http://feedproxy.google.com/~r/pedrokroger/~3/NPL8niHm39I/</link> <comments>http://pedrokroger.com/2010/08/the-python-quick-reference/#comments</comments> <pubDate>Thu, 12 Aug 2010 17:52:42 +0000</pubDate> <dc:creator>Pedro Kroger</dc:creator> <category><![CDATA[latex]]></category> <category><![CDATA[python]]></category> <guid isPermaLink="false">http://pedrokroger.net/blog/?p=249</guid> <description><![CDATA[I uploaded a new version of my Python Quick Reference. You can access it by clicking on the top menu. The Python cheat sheets I found on the internet were either too long, not too pretty, or didn&#8217;t have the source available so I could change it to fit my taste. I designed the Python Quick [...]]]></description> <content:encoded><![CDATA[<p>I uploaded a new version of my <a
title="The Python Quick Reference" href="http://pedrokroger.net/blog/python-quick-reference/">Python Quick Reference</a>. You can access it by clicking on the top menu. The Python cheat sheets I found on the internet were either too long, not too pretty, or didn&#8217;t have the source available so I could change it to fit my taste.</p><p><img
class="s3-img" src="http://images.pedrokroger.net/python-quick-ref.png" border="0" alt="python-quick-ref.png" /></p><p>I designed the Python Quick Reference using LaTeX. I used common packages like <em>color</em>, <em>multicol</em>, and <em>graphicx</em> to have colored text, four columns, and to insert the python logo. I used <a
title="The beramono latex package" href="http://www.tug.dk/FontCatalogue/beramono/">beramono</a> — a &#8220;version of Bitstream Vera Mono slightly enhanced for use with TeX&#8221; — and <a
title="the utopia latex font" href="http://www.tug.dk/FontCatalogue/utopia/">utopia</a> to have better looking fonts. I used the <a
title="tikz package" href="http://www.texample.net/tikz/">tikz</a> package to create the round boxes that separate each section:</p><p><img
style="border: 0px initial initial;" title="Round boxes with tikz" src="http://images.pedrokroger.net/round-boxes.png" border="0" alt="Round boxes with tikz" width="321" height="171" /></p><p>The box creation is abstracted in the <tt>\header</tt> macro:</p><pre>\newcommand{\header}[1]{
  \begin{tikzpicture}
    \node [fill=shade,rounded corners=5pt]
    {
      \parbox{.95\linewidth}{
        \large
        \textcolor{blue}{\sf \textbf{\raisebox{-15pt}{#1}}}
        \vspace*{1ex}
      }
    };
  \end{tikzpicture}
  \par
}</pre><p>With this macro I can create each section with a command like <tt>\header{Built-in functions}</tt>. Simple and easy <img
src='http://pedrokroger.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /></p><p>Finally, I used the <a
title="dirtree package" href="http://www.ctan.org/tex-archive/macros/generic/dirtree/">dirtree package</a> to display the built-in exceptions hierarchy as a tree:</p><p><img
class="s3-img" style="border: 0px initial initial;" title="Built-in exceptions as a tree" src="http://images.pedrokroger.net/ex-built-in-exceptions.png" border="0" alt="Built-in exceptions as a tree" width="255" height="173" /></p><p>I like using something like LaTeX and dirtree because I can copy the exception hierarchy from the Python documentation and have LaTeX display it for me. If the list changes, it&#8217;s easier to update it than if I was using a graphical program. On the other hand I&#8217;m not 100% satisfied with the result, so I&#8217;m looking for another tree package for LaTeX. If you know one that might be good, let me know in the comments.</p><p>If you want something more substantial (and yet short), maybe the <a
title="Python Pocket Reference" href="http://oreilly.com/catalog/9780596158095">Python Pocket Reference</a> is what you&#8217;re looking for. In addition to paper, it&#8217;s available in pdf, epub, and kindle (mobi) formats. (Disclaimer: I don&#8217;t have any affiliation with O&#8217;reilly and the above link it&#8217;s <strong>not</strong> an affiliate link.)</p><p>That&#8217;s it, a simple and good looking cheat sheet in minutes, courtesy of LaTeX. I may include a third page in the future with some useful functions from the standard library. There are also things that I didn&#8217;t figure out how to display in a short space, like data structures, iterators and generators. Please let me know in the comments if you have any ideas or suggestions.</p><p><strong>UPDATE:</strong> Sarabander implemented some fixes and improvements (Thanks!). Go grab the <a
title="New version python quick reference" href="https://github.com/downloads/kroger/python-quick-ref/python-quick-ref.pdf">new version</a>!</p><p>&nbsp;</p><p><a
class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpedrokroger.com%2F2010%2F08%2Fthe-python-quick-reference%2F&amp;title=The%20Python%20Quick%20Reference" id="wpa2a_10"><img
src="http://pedrokroger.com/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p><img src="http://feeds.feedburner.com/~r/pedrokroger/~4/NPL8niHm39I" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pedrokroger.com/2010/08/the-python-quick-reference/feed/</wfw:commentRss> <slash:comments>2</slash:comments> <feedburner:origLink>http://pedrokroger.com/2010/08/the-python-quick-reference/</feedburner:origLink></item> <item><title>Configuring Emacs as a Python IDE</title><link>http://feedproxy.google.com/~r/pedrokroger/~3/P8GoRzdPUjI/</link> <comments>http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/#comments</comments> <pubDate>Thu, 15 Jul 2010 21:48:25 +0000</pubDate> <dc:creator>Pedro Kroger</dc:creator> <category><![CDATA[emacs]]></category> <category><![CDATA[python]]></category> <guid isPermaLink="false">http://pedrokroger.net/blog/?p=81</guid> <description><![CDATA[Emacs is a huge beast. It can read email, play tetris, act as a file manager, display google maps, and even edit videos. It has support for many, many programming languages and has many features related to programming. Unfortunately, emacs doesn&#8217;t have a full programming environment for python out-of-the-box. In this post I&#8217;ll show how to [...]]]></description> <content:encoded><![CDATA[<p>Emacs is a huge beast. It can <a
href="http://www.gnu.org/software/emacs/tour/">read email, play tetris, act as a file manager</a>, <a
href="http://julien.danjou.info/blog/2010.html">display google maps</a>, and even <a
href="http://1010.co.uk/gneve.html">edit videos</a>. It has support for many, many programming languages and has many <a
href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Programs.html">features</a> <a
href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Building.html">related</a> to <a
href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Maintaining.html">programming</a>. Unfortunately, emacs doesn&#8217;t have a full programming environment for python out-of-the-box.</p><p>In this post I&#8217;ll show how to configure emacs to write Python programs. We want to have not only basics things like syntax highlighting, but also code completion, easy access to Python&#8217;s documentation, ability to check for common mistakes, run unit tests, debugging, and a good interactive programming environment.</p><p>This setup is based on <a
href="http://ipython.scipy.org/moin/Documentation">ipython</a> and <a
href="https://launchpad.net/python-mode">python-mode</a>, but it&#8217;s also possible to use <a
href="http://rope.sourceforge.net/">rope</a>, <a
href="http://rope.sourceforge.net/ropemacs.html">ropemacs</a>, and the <a
href="http://cx4a.org/software/auto-complete/">auto complete mode</a> as we can see <a
href="http://www.saltycrane.com/blog/2010/05/my-emacs-python-environment/">here</a>. I didn&#8217;t have much luck with ropemacs in the past but I&#8217;ll try it again in the future.</p><h2>Tools installation and configuration</h2><p>First we should install the tools we need.</p><ul><ul><li><strong>python-mode</strong>. There are two python modes; <em>python.el</em> and <em>python-mode.el</em>. Although <em>python.el</em> comes with GNU Emacs 22, I recommend you use <em>python-mode.el</em> since it has support for ipython. (There&#8217;s some <a
href="http://mail.python.org/pipermail/python-mode/2009-January/000514.html">talk</a> about merging the two modes, but I don&#8217;t know it&#8217;s current status). Download and install <a
href="https://launchpad.net/python-mode">python-mode.el</a> and put the following in your <tt><em>.emacs</em></tt>:<pre class="code">(require 'python-mode)
(add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))</pre></li><li><strong>ipython</strong>. Ipython is a powerful python shell with advanced features and nice code completion. Check <a
href="http://ipython.scipy.org/moin/Documentation">ipython&#8217;s website</a>for documentation and screencasts. If you&#8217;re using debian or ubuntu, install it with:<pre class="code">sudo apt-get install ipython</pre><p>To configure ipython, edit <em>~/.ipython/ipy_user_conf.py</em> and add your options. I like to use <em>ipy_greedycompleter</em> so it will complete things like <tt>"foo".TAB.</tt></li><li><strong>ipython.el</strong>. It allows you to use python-mode with ipython. Download and install <a
href="http://ipython.scipy.org/dist/ipython.el">ipython.el</a> and put the following in your <tt><em>.emacs</em></tt>:<pre class="code">(require 'ipython)</pre></li><li><strong>lambda-mode</strong>. This is only for aesthetics. When you install <em>lambda-mode.el</em> it will display a lambda character (λ) when you type <em>lambda</em>:<a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/emacs-python-lambda-mode/" rel="attachment wp-att-189"><img
class="alignnone size-full wp-image-189" title="Lambda mode in emacs" src="http://images.pedrokroger.net/emacs-python-lambda-mode.png" alt="Lambda mode in emacs" width="302" height="23" /><br
/> </a>The full name &#8220;lambda&#8221; will still be there, emacs is only displaying it differently. I like lambda-mode because it makes the code look shorter, neater, and cooler. Download and install <a
href="http://dishevelled.net/elisp/lambda-mode.el">lambda-mode.el</a> and put the following in your <tt><em>.emacs</em></tt>:</p><pre class="code">(require 'lambda-mode)
(add-hook 'python-mode-hook #'lambda-mode 1)</pre><p>I had to set the variable <em>lambda-symbol</em> to the following, but YMMV:</p><pre class="code">(setq lambda-symbol (string (make-char 'greek-iso8859-7 107)))</pre><p>There are other ways to have pretty lambdas and pretty symbols in emacs, check the <a
href="http://www.emacswiki.org/emacs/PrettySymbol">Emacs Wiki</a> page to see which one you prefer.</li><li><strong>anything</strong>. We will use <a
href="http://www.emacswiki.org/emacs/Anything">anything</a> for code completion. Download and install <a
href="http://www.emacswiki.org/emacs/download/anything.el">anything.el</a>, <a
href="http://www.emacswiki.org/emacs/download/anything-ipython.el">anything-ipython.el</a>, and <a
href="http://www.emacswiki.org/cgi-bin/emacs/download/anything-show-completion.el">anything-show-completion.el</a>, and add the following to your <tt><em>.emacs</em></tt>:<pre class="code">(require 'anything)
(require 'anything-ipython)
(when (require 'anything-show-completion nil t)
   (use-anything-show-completion 'anything-ipython-complete
                                 '(length initial-pattern)))</pre></li><li><strong>Change comint keys</strong>. Comint is a minor-mode to deal with interpreter commands in an emacs buffer. It&#8217;s used by many modes, including ipython. Comint uses <tt>M-p</tt> and <tt>M-n</tt>to cycle backwards and forward through input history. I prefer to use the up and down arrow keys:<pre class="code">(require 'comint)
(define-key comint-mode-map (kbd "M-") 'comint-next-input)
(define-key comint-mode-map (kbd "M-") 'comint-previous-input)
(define-key comint-mode-map [down] 'comint-next-matching-input-from-input)
(define-key comint-mode-map [up] 'comint-previous-matching-input-from-input)</pre></li><li><strong>pylookup</strong>. We will use <a
href="http://taesoo.org/Opensource/Pylookup">pylookup</a>to search python&#8217;s documentation within emacs. First install the python documentation locally. If you use debian or ubuntu you can install it with one command:<pre class="code">apt-get install python2.6-doc</pre><p>If the python documentation is not available as a package for your system, download it from the <a
href="http://docs.python.org/download.html">python website</a> and unzip it somewhere in your computer. Then download <a
href="http://github.com/tsgates/pylookup/zipball/master">pylookup</a> and follow the instructions in the README file. Run pylookup.py to index the database by running:</p><pre class="code">./pylookup.py -u file:///usr/share/doc/python2.6-doc/html</pre><p>This command will generate a database file (<em>pylookup.db</em>). Naturally, you need to put the correct path for the python documentation. Next you need to add the following to your <em>.emacs</em>. Again, replace the values to match your system.</p><pre class="code">(autoload 'pylookup-lookup "pylookup")
(autoload 'pylookup-update "pylookup")
(setq pylookup-program "~/.emacs.d/pylookup/pylookup.py")
(setq pylookup-db-file "~/.emacs.d/pylookup/pylookup.db")
(global-set-key "\C-ch" 'pylookup-lookup)</pre></li><li><strong>autopair</strong>. A common feature in modern editors is to insert pairs of matching elements such as parenthesis, quotes, and braces. There are many ways to do this in emacs and installing <a
href="http://autopair.googlecode.com/svn/trunk/autopair.el">autopair.el</a> is probably the easiest one. You can configure it to work in all modes and exclude the modes you don&#8217;t to have it activated. For instance, I have it configured to work globally, except in the lisp-mode, where I use <a
href="http://www.emacswiki.org/emacs/ParEdit">paredit</a>:</li></ul></ul><pre class="code">(autoload 'autopair-global-mode "autopair" nil t)
(autopair-global-mode)
(add-hook 'lisp-mode-hook
          #'(lambda () (setq autopair-dont-activate t)))</pre><p>I also have the following to in my <em>.emacs</em> to make autopair work with python single and triple quotes:</p><pre class="code">(add-hook 'python-mode-hook
          #'(lambda ()
              (push '(?' . ?')
                    (getf autopair-extra-pairs :code))
              (setq autopair-handle-action-fns
                    (list #'autopair-default-handle-action
                          #'autopair-python-triple-quote-action))))</pre><ul><li><strong>pep8 and pylint</strong>. These scripts are good to check your program for style errors and common mistakes. Install pylint and pep8:<pre class="code">apt-get install pylint pep8</pre><p>and download and install <a
href="http://gist.github.com/raw/302847/3331473995b55cc578e7d63dd82474749367c29c/python-pep8.el">python-pep8.el</a> and <a
href="http://gist.github.com/raw/302848/60961ad1134e7bec5d836857fb67109245548dad/python-pylint.el">python-pylint.el</a> to integrate them with emacs and add the following to your <em>.emacs</em>:</p><pre class="code">(require 'python-pep8)
(require 'python-pylint)</pre></li><li><strong>delete trailing space</strong>. When you type the return key in python-mode it&#8217;ll invoke <em>py-newline-and-indent</em>. As the manual says, it &#8220;deletes the whitespace before point, inserts a newline, and takes an educated guess as to how you want the new line indented.&#8221; This is great and I love this feature, but one unintended consequence is that you may end up with blank lines with trailing spaces. Python doesn&#8217;t care, but the pep8 tool will complain. Put the following in your <em>.emacs</em>to delete the trailing spaces when saving a file:<pre class="code">(add-hook 'before-save-hook 'delete-trailing-whitespace)</pre></li><li><strong>ipdb package</strong>. The <a
href="http://pypi.python.org/pypi/ipdb">ipdb package</a> makes it easy to set breakpoints in the ipdb debugger. It&#8217;s easy to install it using <tt>easy_install</tt>(duh <img
src='http://pedrokroger.com/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' /> ):<pre class="code">easy_install ipdb</pre></li><li><strong>reimport package</strong>. <a
href="http://code.google.com/p/reimport/">reimport</a> is a replacement for Python&#8217;s <em>reload</em> function that reloads all modules and sub-modules consistently. It&#8217;s useful for long-running programs and interactive development. Install it with <tt>easy_install</tt>:<pre class="code">sudo easy_install reimport</pre></li><li><strong>Templates.</strong> <a
href="http://code.google.com/p/yasnippet/">Yasnippet</a> is a textmate-like templates for emacs. Download it <a
href="http://yasnippet.googlecode.com/files/yasnippet-bundle-0.6.1c.el.tgz">here</a> and pet the following in your <em>.emacs</em>:<pre class="code">(require 'yasnippet-bundle)
(yas/initialize)
(yas/load-directory "~/.emacs.d/my-snippets/")</pre></li></ul><p>You can also install <a
href="http://www.emacswiki.org/emacs/FlyMake">flymake</a> to check the syntax on the fly. I find it distracting, so I don&#8217;t use it.</p><p>All right, these are the tools we need! Now we can go on and use these features.</p><h2>Using python-mode</h2><p>So now we&#8217;re ready to go. Open a python file, say <em>test.py</em>, type <tt>C-c !</tt> (<em>py-shell</em>) to start the python interpreter. Go back to <em>test.py</em> (with <tt>C-x o</tt>) and type <tt>C-c C-c</tt> (<em>py-execute-buffer</em>) to send the whole buffer to the interpreter. In the following picture we can see how it works; it&#8217;s neat to be able to write code in one file and test it in the interpreter without the whole edit-compile-run-test cycle:</p><p><a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/emacs-ipyhon/" rel="attachment wp-att-120"><img
class="size-full wp-image-120 alignnone" title="emacs-ipyhon" src="http://images.pedrokroger.net/emacs-ipyhon.png" alt="ipython inside emacs" width="540" height="386" /></a></p><h2>Code completion</h2><p>Code completion is very useful and I find a must to be able to complete methods for both built-in and user-defined classes. For instance, if you type &#8220;os.path.&#8221; and <tt>M-tab</tt> emacs will show all methods available in os.path:</p><p><a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/emacs-python-code-completion-1/" rel="attachment wp-att-123"><img
class="alignnone size-full wp-image-123" title="Python code completion in emacs 1" src="http://images.pedrokroger.net/emacs-python-code-completion-1.png" alt="Python code completion in emacs" width="540" height="500" /></a></p><p>This completion method uses <a
href="http://www.emacswiki.org/emacs/Anything">anything</a> and you can use <tt>C-n</tt> and <tt>C-p</tt> to navigate through the completion items (when you&#8217;re done type return). This works for used-defined methods and functions too:</p><p><a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/emacs-python-code-completion-2/" rel="attachment wp-att-124"><img
class="size-full wp-image-124 alignnone" title="Python code completion in emacs 2" src="http://images.pedrokroger.net/emacs-python-code-completion-2.png" alt="Python code completion in emacs" width="540" height="481" /></a></p><h2>Access to documentation</h2><p>Python has excellent documentation and it&#8217;s a huge bust in productivity to be able to access the documentation without leaving the editor. By using pylookup we can type <tt>C-c h</tt> to search any term in the python documentation. For instance, if we type &#8220;os.path.basename&#8221; and then <tt>C-c h</tt> to invoke the documentation, pylookup will open the documentation page for os.path.basename using the default browser configured in emacs (usually firefox):</p><p><a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/emacs-python-documentation-1/" rel="attachment wp-att-125"><img
class="alignnone size-full wp-image-125" title="Python documentation in emacs 1" src="http://images.pedrokroger.net/emacs-python-documentation-1.png" alt="Python documentation in emacs" width="744" height="542" /></a></p><p>However, many people prefer to use <a
href="http://emacs-w3m.namazu.org/">w3m inside emacs</a> to browse technical documentation. With w3m we can read the documentation without leaving emacs, making it easy to copy code snippets and not needing to switch to an external program (to much switching can kill focus). Here&#8217;s the same documentation in the above picture but using w3m this time:</p><p><a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/emacs-python-documentation-2/" rel="attachment wp-att-126"><img
class="alignnone size-full wp-image-126" title="Python documentation inside emacs 2" src="http://images.pedrokroger.net/emacs-python-documentation-2.png" alt="Python documentation inside emacs" width="720" height="386" /></a></p><p>If you search for something with more than one possible answer, pylookup will ask you to choose among some possibilities, for instance, if I search for <em>print</em> I&#8217;ll get many options to choose from:</p><p><a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/emacs-python-documentation-3/" rel="attachment wp-att-129"><img
class="alignnone size-full wp-image-129" title="Python documentation in emacs 3" src="http://images.pedrokroger.net/emacs-python-documentation-3.png" alt="Python documentation in emacs" width="684" height="291" /></a></p><h2>Code quality</h2><p>The <a
href="http://github.com/jcrocholl/pep8">pep8 script</a> checks if your code follow the <a
href="http://www.python.org/dev/peps/pep-0008/">PEP8 style guide</a>. You can run it inside emacs by typing <tt>M-x pep8</tt>. The key <tt>M-x `</tt> will jump to the place in the source code where the next error occurs:</p><p><a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/emacs-pep8/" rel="attachment wp-att-130"><img
title="Pep8 in emacs" src="http://images.pedrokroger.net/emacs-pep8.png" alt="Pep8 in emacs" width="738" height="424" /></a></p><p>You can run pylint inside emacs with <tt>M-x pylint</tt>, it behaves in a similar way to pep8:</p><p><a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/emacs-pylint/" rel="attachment wp-att-131"><img
class="alignnone size-full wp-image-131" title="Pylint in emacs" src="http://images.pedrokroger.net/emacs-pylint.png" alt="Pylint in emacs" width="657" height="310" /></a></p><h2>Unit tests</h2><p>It&#8217;s possible to run unit tests inside emacs if we use the <a
href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Compilation-Mode.html">compilation mode</a>.  Type <tt>M-x compile</tt> and replace what will appear (most likely &#8220;make -k&#8221;) with your favorite python program to run unit tests. As with pep8 and pylint (they both use the compilation mode), you can type <tt>M-x `</tt> to navigate to the next error. In the following screenshot we can see that <em>test_square_of_100_is_1000</em> is not correct:</p><p><a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/emacs-python-nose/" rel="attachment wp-att-136"><img
class="alignnone size-full wp-image-136" title="Run unit tests inside emacs" src="http://images.pedrokroger.net/emacs-python-nose.png" alt="Run unit tests inside emacs" width="738" height="500" /></a></p><h2>Debugging</h2><p>There are <a
href="http://aymanh.com/python-debugging-techniques">many ways</a> to debug python code. I like to use ipdb, ipython&#8217;s debugger, because it has advanced features like code completion and syntax highlighting. With the <tt>-pdb</tt> flag Ipython will go directly to the debugger when an exception is raised, instead of just printing a stack trace. (you may want to edit <em>~/.ipython/ipythonrc</em> to make the change permanent).</p><p>To set breakpoints in the regular python debugger, you need to add the following lines to your code:</p><pre class="code">import pdb; pdb.set_trace()</pre><p>With the <a
href="http://pypi.python.org/pypi/ipdb">ipdb package</a> we can set breakpoints in a similar way if using ipdb:</p><pre class="code">import ipdb; ipdb.set_trace()</pre><p>I like to make emacs highlight the lines that set breakpoints, so I can easily visualize where the breakpoints are and remember to remove them from the code after I&#8217;m done debugging. I use the following code to accomplish that:</p><pre class="code">(defun annotate-pdb ()
  (interactive)
  (highlight-lines-matching-regexp "import pdb")
  (highlight-lines-matching-regexp "pdb.set_trace()"))
(add-hook 'python-mode-hook 'annotate-pdb)</pre><p>Notice in the following screenshot how the line that sets the breakpoint is highlighted and the program execution stopped at the breakpoint. I used the command <strong>n</strong> (next) to advance to the next statement:</p><h2><a
href="http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/debugging-ipdb-emacs/" rel="attachment wp-att-154"><img
class="alignnone size-full wp-image-154" title="Debugging python with ipdb and emacs" src="http://images.pedrokroger.net/debugging-ipdb-emacs.png" alt="Debugging python with ipdb and emacs" width="720" height="493" /></a></h2><p>I have a function to add breakpoints mapped to <tt>C-c C-t</tt> so I can set breakpoints easily:</p><pre class="code">(defun python-add-breakpoint ()
  (interactive)
  (py-newline-and-indent)
  (insert "import ipdb; ipdb.set_trace()")
  (highlight-lines-matching-regexp "^[ 	]*import ipdb; ipdb.set_trace()"))
(define-key py-mode-map (kbd "C-c C-t") 'python-add-breakpoint)</pre><h2>Templates</h2><p>For textmate-like templates I use <a
href="http://code.google.com/p/yasnippet/">yasnippet</a> (be sure to watch its <a
href="http://www.youtube.com/watch?v=76Ygeg9miao">demo</a>). With it you can define templates easily and quickly to fill things for you, like a new-style class with documentation and an <em>__init__</em> method. Python doesn&#8217;t have much boilerplate, but using yasnippet can help you to write code even faster.</p><h2>Finding your way in the source code</h2><p>Emacs allows us to navigate through source code by using <a
href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Tags.html">tags</a>. When you see a function call you can jump to its definition with <tt>M-.</tt> (<em>find-tag</em>) and jump back with  <tt>M-*</tt> (<em>pop-tag-mark</em>). Another useful command is <em>tags-query-replace</em>, to rename functions, methods, etc. To use it we need to generate a TAGS file. Emacs comes with the <em>etags</em> command but I recommend <a
href="http://ctags.sourceforge.net/">exuberant tags</a>:</p><pre class="code">sudo apt-get install exuberant-ctags</pre><p>Usually I put the following code in a Makefile to generate a TAGS file for a project:</p><pre class="code">ctags-exuberant -e -R --languages=python --exclude="__init__.py"</pre><h2>Dealing with multiple files</h2><p>As we have seen, we can program in an interactive style in python-mode by sending the buffer to the python interpreter with <tt>C-c C-c</tt>. This works well for single file scripts and libraries, but no so well for more complex modules with sub-modules. For instance, if you open <em>file4.py</em> in the <em>mainmodule</em> bellow and execute it with <tt>C-c C-c</tt> it&#8217;ll fail if it depends on other submodules.</p><pre class="code">mainmodule
|--- __init__.py
|--- submodule1
     |--- __init__.py
     |--- file1.py
     |--- file2.py
|--- submodule2
     |--- __init__.py
     |--- file3.py
     |--- file4.py</pre><p>We can define a master file using the <em>py-master-file</em> variable; python-mode will execute the file set in the variable instead of the current buffer&#8217;s file. This variable can be set as a <a
href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables">file variable</a>, but I prefer not to pollute every single freaking .py file in a module with a file variable, so I use a <a
href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Directory-Variables.html">directory variable</a> instead. Another advantage of using directory variables in this case is that each member of a team can set the <em>py-master-file</em> to reflect their file system layout. Create a file called <em>.dir-locals.el</em> in <em>mainmodule</em>&#8216;s root with the following content:</p><pre class="code">((python-mode . ((py-master-file . "/path/to/interactivetest.py")
                 (tags-file-name . "/path/to/TAGS"))))</pre><p>(Note that I also define the tags&#8217; filename, so emacs&#8217;ll automatically load it when I read a python file located in this directory.)</p><p>To make this work I use a master file called <em>interactivetest.py</em> in the module&#8217;s root to re-import the module with the <a
href="http://code.google.com/p/reimport/">reimport</a> package. This file is not really part of the module and I don&#8217;t even check it under version control. Now, every time we hit <tt>C-c C-c</tt>, regardless of what file we are changing, python-mode will execute <em>interactivetest.py</em> again, and update the whole module. For instance, this is what I have in the <em>interactivetest.py</em> for my aristoxenus library:</p><pre class="brush:py">import reimport
import aristoxenus
reimport.reimport(aristoxenus)</pre><p>But I may add a few things in the <em>interactivetest.py</em> file to make testing things interactively easier and to be able to save it between coding sessions:</p><pre class="brush:py">from aristoxenus.parse import humdrum
foo = humdrum.parse_string("**kern\n4C")</pre><p>Of course this is not a substitute for unit tests, but it&#8217;s nice to have <em>foo</em> available in the REPL so I can inspect it and quickly see what&#8217;s going on.</p><h2>Conclusion</h2><p>As you can see, we can have a nice programming environment for python in emacs. It may look like a lot of work, but in reality we only need to download and configure already existing packages. However, it would be nice to have a full-fledged development environment for python like <a
href="http://common-lisp.net/project/slime/">slime</a>.</p><p>I didn&#8217;t mention many things like the <a
href="http://ecb.sourceforge.net/">emacs code browser</a>, the <a
href="http://philjackson.github.com/magit/">git interface</a>, and the <a
href="http://www.emacswiki.org/emacs/EmacsLispScreen">window session manager</a>. They are not particularly specific to python, but they contribute to turn emacs into a powerful tool for development. Maybe I&#8217;ll mention then in another post.</p><p>I intend to make a screencast in the future showing these features, so stay tuned. Meanwhile, what do you use to develop python code?</p><p><a
class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpedrokroger.com%2F2010%2F07%2Fconfiguring-emacs-as-a-python-ide-2%2F&amp;title=Configuring%20Emacs%20as%20a%20Python%20IDE" id="wpa2a_12"><img
src="http://pedrokroger.com/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p><img src="http://feeds.feedburner.com/~r/pedrokroger/~4/P8GoRzdPUjI" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/feed/</wfw:commentRss> <slash:comments>30</slash:comments> <feedburner:origLink>http://pedrokroger.com/2010/07/configuring-emacs-as-a-python-ide-2/</feedburner:origLink></item> <item><title>Python videos</title><link>http://feedproxy.google.com/~r/pedrokroger/~3/-4Xv0O961Dc/</link> <comments>http://pedrokroger.com/2010/06/python-videos/#comments</comments> <pubDate>Fri, 25 Jun 2010 02:21:48 +0000</pubDate> <dc:creator>Pedro Kroger</dc:creator> <category><![CDATA[python]]></category> <category><![CDATA[videos]]></category> <guid isPermaLink="false">http://pedrokroger.net/blog/?p=28</guid> <description><![CDATA[The are quite a bit of nice python videos on the web. In this post I&#8217;ll list some of them. PyCon The videos from the 2009 and 2010 python conference are available at blip. I don&#8217;t like the browser interface in flash, though, so I prefer to browse the archives. A better alternative is to [...]]]></description> <content:encoded><![CDATA[<p>The are quite a bit of nice python videos on the web. In this post I&#8217;ll list some of them.</p><h2>PyCon</h2><p>The videos from the 2009 and 2010 <a
href="http://pycon.org/">python conference</a> are available at <a
href="http://pycon.blip.tv/">blip</a>. I don&#8217;t like the browser interface in flash, though, so I prefer to browse the <a
href="http://pycon.blip.tv/posts?view=archive&amp;nsfw=dc">archives</a>. A better alternative is to check the <a
href="http://us.pycon.org/2010/conference/talks/">talk list</a> at the PyCon website since it has the videos and more information such as slides, abstracts, and biographies.</p><p>These are a few talks I liked:</p><ul><li><a
href="http://us.pycon.org/2010/conference/schedule/event/76/">Understanding the Python GIL</a></li><li><a
href="http://us.pycon.org/2010/conference/schedule/event/139/">PLY and PyParsing</a></li><li><a
href="http://us.pycon.org/2010/conference/schedule/event/7/">Optimizations And Micro-Optimizations In CPython</a></li><li><a
href="http://us.pycon.org/2010/conference/schedule/event/134/">Teaching compilers with python</a></li><li><a
href="http://us.pycon.org/2010/conference/schedule/event/69/">Writing Books using Python and Open Source Software</a></li><li><a
href="http://us.pycon.org/2010/conference/schedule/event/138/">New *and* Improved: Coming changes to unittest, the standard library test framework</a></li><li><a
href="http://us.pycon.org/2010/conference/schedule/event/12/">The Mighty Dictionary</a></li><li><a
href="http://us.pycon.org/2010/conference/schedule/event/71/">Unladen Swallow: fewer coconuts, faster Python</a></li><li><a
href="http://us.pycon.org/2010/conference/schedule/event/96/">Python Metaprogramming</a></li></ul><h2>Showmedo</h2><p>Showmedo is a website with community produced screencasts for free and open-source software. It has a good amount of python videos such as a <a
href="http://showmedo.com/videotutorials/series?name=6WiUOGJBb">series about python 3</a>, some demonstrations of the super cool <a
href="http://showmedo.com/videotutorials/series?name=CnluURUTV">ipython shell</a>, and even videos for <a
href="http://showmedo.com/videotutorials/series?name=AzsZ2afN2">beginners</a>.</p><h2>Google&#8217;s Python Class</h2><p>Google has a <a
href="http://code.google.com/edu/languages/google-python-class/?utm_source=twitterfeed&amp;utm_medium=twitter">full series of lectures</a> about python. If you are just starting to learn the language (or even starting to learn how to program), go check these out!</p><h2>More advanced videos</h2><p>Finally, these are a few more advanced videos and a must watch for any python programmer:</p><ul><li><a
href="http://video.google.com/videoplay?docid=-6459339159268485356#">Python 3000</a>. A talk by Guido himself.</li><li><a
href="http://www.youtube.com/watch?v=E_kZDvwofHY">Advanced Python or Understanding Python</a> is a very nice talk by Thomas Wouters.</li><li><a
href="http://www.youtube.com/watch?v=23s9Wc3aWGY">Slightly Advanced Python: Some Python Internals</a> by python über guru Alex Martelli</li></ul><p>So, go watch those videos and don&#8217;t forget to recommend nice python videos to us.</p><p><a
class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpedrokroger.com%2F2010%2F06%2Fpython-videos%2F&amp;title=Python%20videos" id="wpa2a_14"><img
src="http://pedrokroger.com/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p><img src="http://feeds.feedburner.com/~r/pedrokroger/~4/-4Xv0O961Dc" height="1" width="1"/>]]></content:encoded> <wfw:commentRss>http://pedrokroger.com/2010/06/python-videos/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://pedrokroger.com/2010/06/python-videos/</feedburner:origLink></item> </channel> </rss><!-- Dynamic page generated in 1.226 seconds. --><!-- Cached page generated by WP-Super-Cache on 2012-02-15 16:31:16 -->

