<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>Posts about Python</title>
    <link>http://wiki.futuretoby.com/tag/python</link>
    <language>en-us</language>
    <item>
      <title>Book Review: Python Testing Cookbook</title>
      <description>This is the second of 2 Python book reviews. The book is Python Test Cookbook.&amp;nbsp;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;This book is a very complete overview of all aspects of testing with Python. It starts out with simple unit tests, then moves on to nose, BDD, Doctest, acceptance testing, coverage, continuous integration, and smoke tests and load tests. The last chapter of the book gives you a number of advices for starting out with testing.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;The Good&lt;/h2&gt;&lt;div&gt;I enjoyed this book in that it gave me a birds-eye view of all the tools and techniques that are there for Python, many of which I didn't know about before. I also learn new things about things that I had already used before. Lastly, I liked the last chapter in which the author gives us his heart-felt experiences with testing. Although I don't agree with everything he says(running your tests once a day is way too few), there is a lot of good advice there as well as good stories.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;The Bad&lt;/h2&gt;&lt;div&gt;One thing that I don't like about this book is that it's too code heavy. Pages and pages of code are print onto the page with only interleaving explanations. I mostly skimmed those parts because reading code line-by-line like that is just too boring. Code is simply not meant to be read in a linear fashion. When you read code, you jump between different files rapidly in order to fill the in missing context as you try to gain an understanding of the code. An even better aid in reading code is the ability to execute the code and instrument it with print statements or stop it with the debugger and inspect the program state. So, in summary, code-heavy books just doesn't make sense. Perhaps instead of writing this as a book, we should just point the readers at a code repository?&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;The second problem is that not enough was done to motivate each technique that was used. The author didn't properly motivate why one should write unit tests at all. Or why use a given technique listed in the book. Only cursory introduction is given for each technique or tool, and then it was straight to the code. We dwelled too much time on the how and not on the why, which makes this book very unfriendly to beginners.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;Summing Up&lt;/h2&gt;&lt;div&gt;Overall, I would not recommend this book to beginners or people who are looking for an introduction to testing. I am on the fence about recommending it at all, but it might be helpful for people who are already familiar with test driven development but just haven't been doing it with Python.&lt;/div&gt;</description>
      <pubDate>Tue, 02 Aug 2011 12:47:37 -0500</pubDate>
      <guid>http://wiki.futuretoby.com/Book_Review%3A_Python_Testing_Cookbook</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Book_Review%3A_Python_Testing_Cookbook</link>
    </item>
    <item>
      <title>Book Review: Python 3 Web Development - Beginners Guide</title>
      <description>&lt;i&gt;I just finished reading Python 3 Web Development - Beginners Guide by Michel Anders and here is my book review.&lt;/i&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Michel Anders is no doubt a brilliant programmer. He has managed to go through HTML, Javascript, jQuery, jQuery plugins(both using and writing), jQuery UI, CSS selectors, CSS 3, Python, CherryPy, SQL and SQLite, unit testing, writing your own ORM, and Python meta-classes&amp;nbsp;all in one book! Which is the problem with this book. I doubt any one who qualifies as a beginner will be able to get any further than chapter 2. I believe the author made the mistake of not putting in enough thought about his audience when writing. But, before making my final remarks, I'll give it proper treatment by commenting on each of the chapters.&lt;/div&gt;&lt;h2&gt;Chapter 1&lt;br&gt;&lt;/h2&gt;&lt;div&gt;Chapter 1 explained the authors reasons for choosing the tools that he did, and &lt;i&gt;boy&lt;/i&gt; were there a lot of choices to be made. Here were the choices:&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Web framework: CherryPy&lt;/li&gt;&lt;li&gt;Language: Python 3&lt;/li&gt;&lt;li&gt;Javascript Library: jQuery and jQuery UI&lt;/li&gt;&lt;li&gt;Database: SQLLite&lt;/li&gt;&lt;li&gt;ORM: None. He's rolling his own&lt;/li&gt;&lt;li&gt;Revision Control: svn&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;There are a lot of high level talk about the rationale of each choice and why he made them. It was a bit strange that he put the choice of using Python &lt;i&gt;after&lt;/i&gt; the choice of using CherryPy. The first chapter is quite intimidating for beginners - there is really lots to consider when building a web app. He admits it too, but he puts in a lot of encouraging words to encourage the reader to stay focused.&lt;/div&gt;&lt;h2&gt;Chapter 2&lt;/h2&gt;&lt;div&gt;Chapter 2 went through the exercise of building a web-based spreadsheet application, a la Google Docs. The goal is ambitious, especially for a "hello world" program. I wondered how he was going to pull it off.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;The Author covered CherryPy, jQuery/CSS selectors, a jQuery plugin called jEditable, wrote his own jQuery plugin that builds a spreadsheet which uses jEditable, CSS 3 and HTML all in this chapter. The amount of Javascript in this chapter really surprised me because in the who-is-this-book-for section, it says "introductory level knowledge of JavaScript might be useful, but is not strictly necessary". He simply tried to cram too many things in, explaining each technology only cursorily as he encounters them.&amp;nbsp;&lt;i&gt;I am pretty sure that he lost almost all readers in his audience with this chapter&lt;/i&gt;.&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;h2&gt;The Rest of the Chapters&lt;/h2&gt;&lt;div&gt;Since we've already lost almost all readers I will place less emphasis on chapters 3-10. Basically, it is more of the same: trying to cram too much information into his readers' minds too quickly. These chapters whirl-wind tour the following:&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;Writing an authentication handler, and then later authorization within CherryPy&lt;/li&gt;&lt;li&gt;Using the file system as storage&lt;/li&gt;&lt;li&gt;Using SQLite to replace the file system as as storage&lt;/li&gt;&lt;li&gt;Using SQL directly to manipulate and query the database&lt;/li&gt;&lt;li&gt;Ajax and lots more of jQuery and jQuery UI&lt;/li&gt;&lt;li&gt;Unit testing in Python&lt;/li&gt;&lt;li&gt;Building a hand-rolled ORM, and then improving it using meta-classes, where the phrase "make your head explode" was used&lt;/li&gt;&lt;li&gt;Adding a CRUD interface to the system for his CRM, and then refining the CRM.&lt;/li&gt;&lt;/ul&gt;&lt;div&gt;The further you get in the book, the larger blocks of code were put on the page, and the author just tries to talk through what is going on. I skimmed most of these chapters because when you are explaining code that is so dense, it is easier to read the code itself - which I often resorted to - than to read the prose.&lt;/div&gt;&lt;/div&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;div&gt;Unfortunately, I cannot recommend this book. Reading from the book title, the audience is a Python programmer, perhaps beginner to intermediate, who is beginning in building web applications. This book will send this programmer away crying. I think perhaps a more fitting title for this book is "A Coding Cowboy's Journey In Web Development with Python 3".&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;/div&gt;</description>
      <pubDate>Thu, 21 Jul 2011 23:54:14 -0500</pubDate>
      <guid>http://wiki.futuretoby.com/Book_Review%3A_Python_3_Web_Development_-_Beginners_Guide</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Book_Review%3A_Python_3_Web_Development_-_Beginners_Guide</link>
    </item>
    <item>
      <title>Python Book Reviews Forthcoming</title>
      <description>The kind folks at&amp;nbsp;&lt;a href="http://www.PacktPub.com"&gt;PacktPub&lt;/a&gt;&amp;nbsp;are letting me review a couple of Python books. Hooray! They are&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;&lt;span class="Apple-style-span" style="font-family: Calibri; line-height: normal; word-spacing: 0px; font-size: medium; border-collapse: collapse; "&gt;&lt;a href="http://www.packtpub.com/python-3-web-development-beginners-guide/book" target="_blank" style="color: rgb(34, 34, 34); "&gt;Python 3 Web Development Beginner's Guide&lt;/a&gt;&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span class="Apple-style-span" style="font-family: Calibri; line-height: normal; word-spacing: 0px; font-size: medium; border-collapse: collapse; "&gt;&lt;a href="http://www.packtpub.com/python-testing-cookbook/book" target="_blank" style="color: rgb(34, 34, 34); "&gt;Python Testing Cookbook&lt;/a&gt;&lt;/span&gt;&lt;br&gt;&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;Look for my reviews of them in the near future.&lt;/div&gt;</description>
      <pubDate>Fri, 15 Jul 2011 10:38:09 -0500</pubDate>
      <guid>http://wiki.futuretoby.com/Python_Book_Reviews_Forthcoming</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Python_Book_Reviews_Forthcoming</link>
    </item>
    <item>
      <title>Smart Parameter Checks in Python</title>
      <description>While I really enjoy using Michael Foord's&amp;nbsp;&lt;a href="http://www.voidspace.org.uk/python/mock/"&gt;Mock library&lt;/a&gt;, there is one thing missing and I thought would be a fun project to add - which is the subject of this post.&lt;h2&gt;Fun with Parameters&lt;/h2&gt;&lt;div&gt;Python has the most sophisticated function parameter calling mechanics I've ever seen. Given a function f&lt;/div&gt;&lt;div&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;def f(a, b):&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; font-family: monospace; font-size: 11px; background-color: rgb(238, 238, 238); "&gt;    return a + b&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;You can either call it like normal(positional parameters)&lt;/div&gt;&lt;pre&gt;f(1, 2)&lt;/pre&gt;&lt;div&gt;or by keyword parameter&lt;/div&gt;&lt;pre&gt;f(a=1, b=2)&lt;/pre&gt;&lt;div&gt;With keyword parameters, the position doesn't matter anymore, so the above call is equivalent to&lt;/div&gt;&lt;pre&gt;f(b=2, a=1)&lt;/pre&gt;&lt;div&gt;You can even mix positional and keyword parameters, as long as you put all the positionals first&lt;/div&gt;&lt;pre&gt;f(1, b=2)&lt;/pre&gt;&lt;div&gt;So, all the ways I've listed of calling the function f with the parameter a as 1 and b as 2 will have the same functional behavior, given what we know of the signature of the function. So, it would be logical that the mock library would consider&lt;/div&gt;&lt;pre&gt;f.assert_called_with(a=1, b=2)&lt;/pre&gt;&lt;div&gt;a passing assertion even though&amp;nbsp;in reality it was called as&lt;/div&gt;&lt;pre&gt;f(1, 2)&lt;/pre&gt;&lt;div&gt;but alas, it does not.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;With that, it was my mission to make this happen!&lt;/div&gt;&lt;h2&gt;Proof-of-Concept&lt;/h2&gt;&lt;div&gt;First I created a prototype/proof-of-concept. See&amp;nbsp;&lt;a href="https://github.com/airportyh/smart_param_check.py"&gt;code here&lt;/a&gt;. Using&lt;/div&gt;&lt;pre&gt;&lt;font class="Apple-style-span" face="'Bitstream Vera Sans Mono', Courier, monospace" size="2"&gt;&lt;span class="Apple-style-span" style="line-height: 16px; word-spacing: 0px;"&gt;&lt;span class="Apple-style-span" style="font-size: 12px; line-height: 17px; "&gt;&lt;span class="n" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;inspect&lt;/span&gt;&lt;span class="o" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; font-weight: bold; "&gt;.&lt;/span&gt;&lt;span class="n" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;getargspec&lt;/span&gt;&lt;span class="p" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;(&lt;/span&gt;&lt;span class="bp" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; color: rgb(153, 153, 153); "&gt;self&lt;/span&gt;&lt;span class="o" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; font-weight: bold; "&gt;.&lt;/span&gt;&lt;span class="n" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;func&lt;/span&gt;&lt;span class="p" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;)&lt;/span&gt;&lt;/span&gt;&lt;br&gt;&lt;/span&gt;&lt;/font&gt;&lt;/pre&gt;&lt;div&gt;I was able to get all the info about the signature of a function I needed. When a function call actually comes in, my callable receives them as&lt;/div&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="font-family: 'Bitstream Vera Sans Mono', Courier, monospace; font-size: 12px; line-height: 17px; word-spacing: 0px; "&gt;&lt;span class="k" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; font-weight: bold; "&gt;def&lt;/span&gt; &lt;span class="nf" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; color: rgb(153, 0, 0); font-weight: bold; "&gt;__call__&lt;/span&gt;&lt;span class="p" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;(&lt;/span&gt;&lt;span class="bp" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; color: rgb(153, 153, 153); "&gt;self&lt;/span&gt;&lt;span class="p" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;,&lt;/span&gt; &lt;span class="o" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; font-weight: bold; "&gt;*&lt;/span&gt;&lt;span class="n" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;args&lt;/span&gt;&lt;span class="p" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;,&lt;/span&gt; &lt;span class="o" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; font-weight: bold; "&gt;**&lt;/span&gt;&lt;span class="n" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;kwds&lt;/span&gt;&lt;span class="p" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; line-height: 1.4em; "&gt;):&lt;/span&gt;&lt;/span&gt;&lt;br&gt;&lt;/pre&gt;&lt;div&gt;at which point, I resolve all the parameters with the parameter list in the function signature(I called this "combining" the args)&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;First, by walking the actual positionals (the &lt;i&gt;args&lt;/i&gt; array coming in) and cross referencing them with the ones in the function signature. After this is done, we basically converted the positionals into named form - as a dict.&lt;/li&gt;&lt;li&gt;Then merge everything in &lt;i&gt;kwds&lt;/i&gt;&amp;nbsp;into the same dict. So we have one unified dict with all the actually parameters and keyed by parameter name.&lt;/li&gt;&lt;li&gt;If there are any left over from the variable position args, they are stored in an &lt;i&gt;extras&lt;/i&gt;&amp;nbsp;list.&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;Now, with this information handy, we can actually do our own safe parameter checking, and we should! So when a call is made, I also check if all the required params have been provided, whether there are any unexpected params and so forth, and actually raise some TypeErrors like a real function if need be.&lt;/div&gt;&lt;/div&gt;&lt;div&gt;But the better part is what comes next - we can now implement the &lt;i&gt;assert_called_with&lt;/i&gt; with these new semantics. When a call to &lt;i&gt;assert_called_with&lt;/i&gt; is called, I "combine" the args coming into that call, and check if they match the previously made function call. It's that simple!&lt;/div&gt;&lt;h2&gt;Working in Python-Mock&lt;/h2&gt;&lt;div&gt;Well great. But we still can't use for the Mock library. So I did some more hacking on a&amp;nbsp;&lt;a href="http://code.google.com/r/airportyh-python-mock/source/browse/?r=smart-param-check"&gt;branch of Foord's code&lt;/a&gt;. Not sure it's the cleanest code, but it now works if you want to try it out&lt;/div&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="font-family: arial, sans-serif; font-size: 13px; line-height: normal; white-space: normal; word-spacing: 0px; "&gt;&lt;tt id="checkoutcmd" style="font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Lucida Console', monospace; font-size: 12px; "&gt;hg clone https://airportyh-python-mock.googlecode.com/hg/ airportyh-python-mock&lt;/tt&gt;&amp;nbsp;&lt;/span&gt;&lt;br&gt;&lt;/pre&gt;&lt;div&gt;The way you use it with the Mock library is through &lt;i&gt;mocksignature&lt;/i&gt;.&amp;nbsp;&lt;/div&gt;&lt;pre&gt;from mock import mocksignature&lt;/pre&gt;&lt;div&gt;&lt;i&gt;mocksignature&lt;/i&gt;&amp;nbsp;wraps a function that you pass it and uses the signature of that function as a guide. Given the function &lt;i&gt;f&lt;/i&gt;&amp;nbsp;that we had previously, you can do&lt;/div&gt;&lt;pre&gt;f = mocksignature(f)&lt;/pre&gt;&lt;div&gt;now call it&lt;/div&gt;&lt;pre&gt;f(1, 2)&lt;/pre&gt;&lt;div&gt;and then checking the associated mock with a different call style&lt;/div&gt;&lt;pre&gt;f.mock.assert_called_with(a=1, b=2)&lt;/pre&gt;&lt;div&gt;should now pass.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Cheers!&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;</description>
      <pubDate>Thu, 24 Mar 2011 22:27:29 -0500</pubDate>
      <guid>http://wiki.futuretoby.com/Smart_Parameter_Checks_in_Python</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Smart_Parameter_Checks_in_Python</link>
    </item>
    <item>
      <title>Python-Style OO in Javascript</title>
      <description>A while a go I wrote a post on&amp;nbsp;&lt;a href="http://tobyho.com/Prototype_Inheritence_in_Python"&gt;Prototype Inheritence in Python&lt;/a&gt;. This time, I am somewhat going the opposite direction. That's right: &lt;i&gt;Python-Style OO in Javascript&lt;/i&gt;.&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Now, I don't think I am the first one who thought of this. In fact, prototype.js does something like this for their method extensions to DOM objects. The main idea is this: if you specify &lt;i&gt;self&lt;/i&gt;&amp;nbsp;as the first argument to a method explicitly, you will be able to use &lt;i&gt;self&lt;/i&gt;&amp;nbsp;inside of nested closures within the method without having to create a &lt;i&gt;self&lt;/i&gt;&amp;nbsp;variable manually, i.e.:&lt;/div&gt;&lt;pre&gt;var self = this&lt;/pre&gt;&lt;div&gt;or doing something like Function.prototype.bind, or pass the context explicitly around like the&amp;nbsp;&lt;i&gt;&lt;a href="http://github.com/airportyh/ecma5array/blob/master/ecma5array.js"&gt;Array methods forEach, map, every, etc&lt;/a&gt;.&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;br&gt;&lt;/i&gt;&lt;/div&gt;&lt;div&gt;This is but a small proof-of-concept. The result is you can write a class like this:&lt;/div&gt;&lt;pre&gt;var Man = Class(Object)({
  __init__: function(self, name){
    self.name = name
  },
  greeting: function(self, other){
    setTimeout(function(){
      self.say("Hello, " + other.name + ", my name is " + self.name)
    }, 100)
  },
  say: function(self, msg){
    sys.puts(msg)
  }
})&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Take it for a spin:&lt;/div&gt;&lt;pre&gt;var dan = new Man('Dan')
var john = new Man('John')
dan.greeting(john)
john.say('How do?')&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Output:&lt;/div&gt;&lt;pre&gt;How do?
Hello, John, my name is Dan
&lt;/pre&gt;&lt;div&gt;The implementation of &lt;i&gt;Class&lt;/i&gt;&amp;nbsp;looks like this:&lt;/div&gt;&lt;pre&gt;function toArray(args){
  var ret = []
  for (var i = 0; i &amp;lt; args.length; i++)
    ret.push(args[i])
  return ret
}

function Class(parent){
  function bind(func, obj){
    var ret = function(){
      var args = toArray(arguments)
      args.splice(0, 0, obj)
      return func.apply(undefined, args)
    }
    return ret
  }
  
  return function(attrs){
    return function(){
      for (var name in attrs){
        var value = attrs[name]
        if (typeof(value) == 'function'){
          this[name] = bind(value, this)
          this[name].name = name
        }else{
          this[name] = value
        }
      }
      this.__init__.apply(this, arguments)
    }
  }
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Full source can be found&amp;nbsp;&lt;a href="http://github.com/airportyh/misc/blob/master/python_like_oo/play.js"&gt;here&lt;/a&gt;. I ran it in&amp;nbsp;&lt;a href="http://nodejs.org/"&gt;node&lt;/a&gt;. This could be an interesting approach to avoiding "&lt;i&gt;this-&lt;/i&gt;hell".&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;span class="Apple-style-span" style="font-style: normal; "&gt;&lt;br&gt;&lt;/span&gt;&lt;/i&gt;&lt;/div&gt;</description>
      <pubDate>Wed, 16 Jun 2010 23:47:47 -0500</pubDate>
      <guid>http://wiki.futuretoby.com/Python-Style_OO_in_Javascript</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Python-Style_OO_in_Javascript</link>
    </item>
    <item>
      <title>One-Liner WebServer with Python</title>
      <description>Turns out, even better than my&amp;nbsp;&lt;a href="HTTP Server in 5 Lines With Webrick"&gt;HTTP Server in 5 Lines With Webrick&lt;/a&gt;&amp;nbsp;is this one-liner:&lt;pre&gt;python -m SimpleHTTPServer&lt;br&gt;&lt;/pre&gt;&lt;div&gt;This will serve on port 8000 by default, but you can add the port number as the last argument to override. Nice! Credits go to&amp;nbsp;&lt;a href="http://www.catonmat.net/blog/top-ten-one-liners-from-commandlinefu-explained"&gt;this article&lt;/a&gt;.&lt;/div&gt;</description>
      <pubDate>Mon, 26 Apr 2010 10:43:33 -0500</pubDate>
      <guid>http://wiki.futuretoby.com/One-Liner_WebServer_with_Python</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/One-Liner_WebServer_with_Python</link>
    </item>
    <item>
      <title>Get Argumentative with Javascript</title>
      <description>When I looked at the Google Maps API for Javascript, I couldn't help but notice that all the functions in the API Reference look kinda Pythonic. Functions call be call with a positional argument list like normal, i.e.:&lt;pre&gt;new GMap2(&lt;i&gt;mynode&lt;/i&gt;, &lt;i&gt;myopts&lt;/i&gt;)&lt;/pre&gt;&lt;div&gt;or by name with an object literal:&lt;/div&gt;&lt;pre&gt;new GMap2({node: &lt;i&gt;mynode&lt;/i&gt;, opts: &lt;i&gt;myopts&lt;/i&gt;})&lt;/pre&gt;&lt;div&gt;Moreover, arguments can be optional, and they are denoted in the doc with a &lt;i&gt;?&lt;/i&gt;&amp;nbsp;at the end. Finally, the type of each argument is specified.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Here is an example of their API:&lt;/div&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="font-family: monospace, Arial, sans-serif; line-height: 16px; white-space: normal; word-spacing: 0px; border-collapse: collapse; color: rgb(0, 112, 0); "&gt;GMap2(container:Node, opts?:&lt;a href="http://code.google.com/apis/maps/documentation/reference.html#GMapOptions" title="GMapOptions" style="color: rgb(0, 0, 204); "&gt;GMapOptions&lt;/a&gt;)&lt;/span&gt;&lt;br&gt;&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;I thought: &lt;i&gt;How cool is this!!?? I want this!!&lt;/i&gt;&amp;nbsp;But, as the Maps API is proprietary, I couldn't get hold of their source. So, it was time for a little hacking...&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;My immediate goals were: &lt;i&gt;argument validation&lt;/i&gt;, &lt;i&gt;named argument passing&lt;/i&gt;, &lt;i&gt;and optional arguments.&lt;/i&gt;&amp;nbsp;Now I have a prototype with these three things working.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;i&gt;Argument Validation&lt;/i&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;Argument validation in my terms means checking the input arguments to a function when it is called to see if they are valid. The most basic of these checks is whether the number of arguments is correct. Example, we start with a simple &lt;i&gt;add&lt;/i&gt; function:&lt;/div&gt;&lt;pre&gt;function add(one, other){&lt;/pre&gt;&lt;pre&gt;  return one + other;&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;div&gt;Then we &lt;i&gt;enhance&lt;/i&gt;&amp;nbsp;it by wrapping in with the $f function:&lt;/div&gt;&lt;pre&gt;add = $f(add);&lt;/pre&gt;&lt;div&gt;The new enhanced add function now will require the argument list to match up with what is expected:&lt;/div&gt;&lt;pre&gt;&amp;gt; add(1,1)
  2
&amp;gt; add(1)
  Error: Argument 'other' of function add(one, other) was not specified.
&amp;gt; add(1,2,3)
  Error: function add(one, other) expected 2 arguments but got 3: (1, 2, 3).&lt;br&gt;&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;&lt;i&gt;Named Argument Passing&lt;/i&gt;&lt;/b&gt;&lt;/div&gt;&lt;div&gt;Named argument passing is something that Python programmers enjoy, but in Javascript you can simulate it using map literals. For example, given the add function defined above, you can now also write:&lt;/div&gt;&lt;pre&gt;&amp;gt; add({one: 1, other: 2});&lt;/pre&gt;&lt;pre&gt;  3&lt;/pre&gt;&lt;div&gt;The order does not matter because it is a map, so the above is equivalent to:&lt;/div&gt;&lt;pre&gt;&amp;gt; add({other: 2, one: 1});&lt;br&gt;&lt;/pre&gt;&lt;pre&gt;  3&lt;/pre&gt;&lt;div&gt;You can also mix positional and named arguments just like in Python:&lt;/div&gt;&lt;pre&gt;&amp;gt; add(1, {other: 2});&lt;/pre&gt;&lt;pre&gt;  3&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;b&gt;Optional Arguments&lt;/b&gt;&lt;/i&gt;&lt;/div&gt;&lt;div&gt;Optional arguments is another great Python feature. It is really the feature that makes named argument passing worthwhile. In Python we have a nice syntax to specify the default value for an optional argument:&lt;/div&gt;&lt;pre&gt;def f(x=0):&lt;/pre&gt;&lt;pre&gt;  return x * 2&lt;/pre&gt;&lt;div&gt;In Javascript, not so lucky. I had to resort to this:&lt;/div&gt;&lt;pre&gt;f = $f(&lt;/pre&gt;&lt;pre&gt;  {x: 0},&lt;/pre&gt;&lt;pre&gt;  function f(x){&lt;/pre&gt;&lt;pre&gt;    return x * 2;&lt;/pre&gt;&lt;pre&gt;  }&lt;/pre&gt;&lt;pre&gt;)&lt;/pre&gt;&lt;div&gt;Not so bad? Maybe? I am trying to make it look like a decorator/annotation. So, with this code, you can do:&lt;/div&gt;&lt;pre&gt;&amp;gt; f()&lt;/pre&gt;&lt;pre&gt;  0&lt;/pre&gt;&lt;div&gt;Just what you'd expect.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;The combination of named argument passing and optional arguments enable very concise code in some situations. Example, let's say you have a function that generates an html input element given a bunch of parameters:&lt;/div&gt;&lt;pre&gt;function input(type, name, value, classes){
  return '&amp;lt;input \
    type="' + type + '" \
    name="' + name + '" \
    value="' + value + '" \
    class="' + classes.join(' ') + '"&amp;gt;';
}&lt;br&gt;&lt;/pre&gt;&lt;div&gt;In this case, &lt;i&gt;type&lt;/i&gt;&amp;nbsp;and &lt;i&gt;name&lt;/i&gt;&amp;nbsp;are required. &lt;i&gt;V&lt;/i&gt;&lt;i&gt;alue&lt;/i&gt;&amp;nbsp;is required by the spec but we can just default it to ''. &lt;i&gt;Classes&lt;/i&gt;&amp;nbsp;is optional and we'll just default it to [] to avoid a check for null.&lt;/div&gt;&lt;div&gt;So the code to do that is:&lt;/div&gt;&lt;pre&gt;input = $f({value: '', classes: []}, input)&lt;br&gt;&lt;/pre&gt;&lt;div&gt;And now you call call the function in these variety of ways:&lt;/div&gt;&lt;pre&gt;&amp;gt; input('text', 'age')
  &amp;lt;input     type="text"     name="age"     value=""     class=""&amp;gt;
&amp;gt; input({type: 'text', name: 'age'})
  &amp;lt;input     type="text"     name="age"     value=""     class=""&amp;gt;
&amp;gt; input({type: 'text', name: 'age', classes:['text', 'age']})
  &amp;lt;input     type="text"     name="age"     value=""     class="text age"&amp;gt;&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Nice!&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;The code for this prototype is as usual&amp;nbsp;&lt;a href="http://github.com/airportyh/misc/tree/557762272d670370ed172f75f0e041c3a67b2d38/argumentative"&gt;on github&lt;/a&gt;. The next on my todo list is to implement variable length argument list and extra keyword argument lists. So stay tuned.&lt;/div&gt;</description>
      <pubDate>Mon, 29 Jun 2009 23:56:28 -0500</pubDate>
      <guid>http://wiki.futuretoby.com/Get_Argumentative_with_Javascript</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Get_Argumentative_with_Javascript</link>
    </item>
    <item>
      <title>Prototype Inheritence in Python</title>
      <description>&lt;span class="Apple-style-span" style="font-style: italic;"&gt;One of Toby's favorite pastimes is to take concepts from one language and realize it in another.&lt;/span&gt; &lt;span class="Apple-style-span" style="font-style: italic;"&gt;In this episode: Toby implements Javascript-style prototype inheritence in Python.&lt;/span&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="font-style: italic;"&gt;&lt;br&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;One thing that is super cool about Javascript is the fact that objects are just maps. Not only can you add attributes dynamically at any point, you can also add methods dynamically. In Python, you can add methods dynamically, but normally you'd have to add it into the class. But there are cases when you don't want to bother making a class. This inspired me to see how far I can go in making Python behave more like Javascript.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;Introducing prototype.py&lt;br&gt;&lt;/h2&gt;&lt;div&gt;prototype.py lets you write code in Python with Javascript-style prototype inheritence semantics. If you are not familiar with prototype inheritence, just read on for now. I will link to some resources at the end. Now, let's see how to use this bad boy. First you import the module:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; from prototype import *&lt;/pre&gt;&lt;div&gt;To create a &lt;span class="Apple-style-span" style="font-style: italic;"&gt;constructor(we don't really have classes anymore)&lt;/span&gt;, you write a function with the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;@constructor&lt;/span&gt;&amp;nbsp;decorator:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; @constructor
... def Person(this, first, last):
...   this.firstName = first
...   this.lastName = last
...
&amp;gt;&amp;gt;&amp;gt; Person
&amp;lt;constructor 'Person'&amp;gt;&lt;br&gt;&lt;/pre&gt;&lt;div&gt;I am going to use &lt;span class="Apple-style-span" style="font-style: italic;"&gt;this&lt;/span&gt;&amp;nbsp;rather than &lt;span class="Apple-style-span" style="font-style: italic;"&gt;self&lt;/span&gt;&amp;nbsp;and &lt;span class="Apple-style-span" style="font-style: italic;"&gt;camelCase&lt;/span&gt; rather than &lt;span class="Apple-style-span" style="font-style: italic;"&gt;under_scores&lt;/span&gt; for prototype-style code, because, well...Dorothy, we are not in Kansas anymore.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Now you can do:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; bird = Person('Charlie', 'Parker')
&amp;gt;&amp;gt;&amp;gt; bird.firstName
'Charlie'
&amp;gt;&amp;gt;&amp;gt; bird.lastName
'Parker'&lt;br&gt;&lt;/pre&gt;&lt;div&gt;You can add attributes to the object just like in normal Python. But unlike in normal Python, which would raise an&amp;nbsp;&lt;span class="Apple-style-span" style="font-style: italic;"&gt;AttributeError&lt;/span&gt;&amp;nbsp;when trying to access non-existent attributes, in prototype-land it merely returns None:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; print bird.age&lt;/pre&gt;&lt;pre&gt;None&lt;/pre&gt;&lt;div&gt;You can dynamically add a method to the instance just by tagging on a function:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; def sing(this):
...   print '%s sings!!' % this.lastName
...
&amp;gt;&amp;gt;&amp;gt; bird.sing = sing
&amp;gt;&amp;gt;&amp;gt; bird.sing()
Parker sings!!&lt;br&gt;&lt;/pre&gt;&lt;div&gt;This affects only the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;bird&lt;/span&gt;&amp;nbsp;instance. If you want the method to be added to all instances of &lt;span class="Apple-style-span" style="font-style: italic;"&gt;Person&lt;/span&gt;&amp;nbsp;however, you can add it to the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;prototype&lt;/span&gt;&amp;nbsp;of &lt;span class="Apple-style-span" style="font-style: italic;"&gt;Person&lt;/span&gt;.&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; Person.prototype.sing = sing&lt;/pre&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; monk = Person('Thelonious', 'Monk')&lt;/pre&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; monk.sing()&lt;/pre&gt;&lt;pre&gt;Monk sings!!&lt;/pre&gt;&lt;div&gt;This works because &lt;span class="Apple-style-span" style="font-style: italic;"&gt;Person.prototype&lt;/span&gt;&amp;nbsp;is the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;prototype&lt;/span&gt;&amp;nbsp;of the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;monk&lt;/span&gt;&amp;nbsp;instance. In code, this means:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; monk.__proto__ == Person.prototype&lt;/pre&gt;&lt;pre&gt;True&lt;/pre&gt;&lt;div&gt;When the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;sing&lt;/span&gt;&amp;nbsp;attribute is not found on the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;monk&lt;/span&gt;&amp;nbsp;instance itself, it will follow the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;__proto__&lt;/span&gt;&amp;nbsp;reference and look it up in its&lt;span class="Apple-style-span" style="font-style: italic;"&gt;&amp;nbsp;&lt;/span&gt;prototype, which is also referred to as its&amp;nbsp;&lt;span class="Apple-style-span" style="font-style: italic;"&gt;parent&lt;/span&gt;. We can manipulate the parent link:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; monkJr = Person('T.S.', 'Monk')&lt;/pre&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; monkJr.__proto__ = monk&lt;/pre&gt;&lt;div&gt;so that now &lt;span class="Apple-style-span" style="font-style: italic;"&gt;monkJr&lt;/span&gt;&amp;nbsp;inherits all of &lt;span class="Apple-style-span" style="font-style: italic;"&gt;monk's &lt;/span&gt;attributes:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; monk.hair = 'black and curly'&lt;/pre&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; monkJr.hair&lt;/pre&gt;&lt;pre&gt;'black and curly'&lt;/pre&gt;&lt;div&gt;The following are some other properties demonstrating the prototype inheritence model:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; assert monkJr.constructor == monk.constructor == Person&lt;/pre&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; assert Object.prototype.constructor == Object&lt;/pre&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; assert Person.prototype.constructor == Person&lt;/pre&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; assert Person.prototype.__proto__ == Object.prototype&lt;/pre&gt;&lt;div&gt;If this seems confusing, remember that in prototype-land, there are two kinds of things: &lt;span class="Apple-style-span" style="font-style: italic;"&gt;constructors&lt;/span&gt;&amp;nbsp;and &lt;span class="Apple-style-span" style="font-style: italic;"&gt;instances&lt;/span&gt;. The prototype of a constructor is nothing more than an instance of the type that the constructor represents. A new instance returned from calling a constructor will have its parent set to the prototype of the constructor.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;Things You Can't Do in Javascript, i.e. the 1+1&amp;gt;2 Effect&lt;br&gt;&lt;/h2&gt;&lt;div&gt;Python is a more powerful and flexible language than Javascript, so, why am I dumbbing it down to Javascript's level? To show that I am &lt;span class="Apple-style-span" style="font-style: italic;"&gt;not&lt;/span&gt;&amp;nbsp;trying to do that at all, let me point out that there are at least a couple of really cool things you can do with prototype.py that you can't with Javascript, simply due to the fact that it is in Python.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;The first thing is properties. With prototype.py, you can add properties to objects like so:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; def getName(this):
...   return '%s %s' % (this.firstName, this.lastName)
...
&amp;gt;&amp;gt;&amp;gt; Person.prototype.name = property(getName)
&amp;gt;&amp;gt;&amp;gt; bird.name
'Charlie Parker'&lt;br&gt;&lt;/pre&gt;&lt;div&gt;You can also specify setters and deleters in the way you'd expect:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; def setName(this, name):
...   first, last = name.split(' ')
...   this.firstName = first
...   this.lastName = last
...
&amp;gt;&amp;gt;&amp;gt; def deleteName(this):
...   del this.firstName
...   del this.lastName
...
&amp;gt;&amp;gt;&amp;gt; Person.prototype.name = property(getName, setName, deleteName)
&amp;gt;&amp;gt;&amp;gt; bird.name = 'Dizzy Gillespie'
&amp;gt;&amp;gt;&amp;gt; bird.name
'Dizzy Gillespie'
&amp;gt;&amp;gt;&amp;gt; del bird.name
&amp;gt;&amp;gt;&amp;gt; bird.name
'None None'&lt;br&gt;&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;The second thing is&amp;nbsp;&lt;a href="/Parameter_List_Chaining_in_Python"&gt;named parameters, keyword parameters and optional parameters&lt;/a&gt;. Let's just do an example with keyword parameters. Let's say I just wanted a way to easily create ad-hoc objects as key-value pairs, I could write:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; @constructor&lt;/pre&gt;&lt;pre&gt;... def Data(this, **kwargs):
...   for key in kwargs.keys():
...     setattr(this, key, kwargs[key])
...&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Which lets me write:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; project = Data(project='prototype.py', language='python')&lt;br&gt;&lt;/pre&gt;&lt;div&gt;But, I could also define methods and properties in this way:&lt;/div&gt;&lt;pre&gt;&amp;gt;&amp;gt;&amp;gt; file = Data(fileName='prototype.py', fileExt=property(&lt;span class="Apple-style-span" style="font-style: italic;"&gt;getExt)&lt;/span&gt;,&amp;nbsp;&lt;/pre&gt;&lt;pre&gt;                    read=&lt;span class="Apple-style-span" style="font-style: italic;"&gt;read&lt;/span&gt;, write=&lt;span class="Apple-style-span" style="font-style: italic;"&gt;write&lt;/span&gt;)&lt;/pre&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="font-style: italic;"&gt;Sweet!&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;A Note About the Implementation&lt;br&gt;&lt;/h2&gt;&lt;div&gt;The implementation of prototype.py is only about 60 lines of Python at time of writing, would have gone down to 40 without property support. The code can be found&amp;nbsp;&lt;a href="http://github.com/airportyh/misc/tree/86d360ef5b449f4d2ceb795fbf6015341a82d491/prototype.py"&gt;here.&lt;/a&gt;&amp;nbsp;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;A big discovery that enabled me to do this was the&amp;nbsp;&lt;a href="/http://docs.python.org/library/new.html"&gt;new&lt;/a&gt;&amp;nbsp;module. It allowed me to take a function and make it into an instance method by binding it to an object:&lt;/div&gt;&lt;pre&gt;method = new.instancemethod(&lt;span class="Apple-style-span" style="font-style: italic;"&gt;function&lt;/span&gt;, &lt;span class="Apple-style-span" style="font-style: italic;"&gt;object&lt;/span&gt;)&lt;br&gt;&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Another note is that I made the design decision that for methods, I chose to store the unbound function rather than the bound method in the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;__dict__&lt;/span&gt;&amp;nbsp;of the object. I would then bind the function on the fly when it's asked for. This made it very easily to inherit methods because you don't have to worry that the method is really bound to the parent rather than the instance in question.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;h2&gt;Further Reading About Prototype Inheritence&lt;br&gt;&lt;/h2&gt;&lt;div&gt;If you want to learn more about prototype inheritence, try:&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;&lt;a href="http://mckoss.com/jscript/object.htm"&gt;Mike Koss' article&lt;/a&gt;&lt;br&gt;&lt;/li&gt;&lt;li&gt;the &lt;a href="http://en.wikipedia.org/wiki/Prototype-based_programming"&gt;Wikipedia article&lt;/a&gt;&lt;/li&gt;&lt;li&gt;my short post trying to&amp;nbsp;&lt;a href="/Dissecting_the_Prototype_Chaining"&gt;Dissect the Prototype Chaining&lt;/a&gt;&lt;/li&gt;&lt;li&gt;or if you have a lot of time,&amp;nbsp;&lt;a href="http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html"&gt;this lengthy essay from Stevey.&lt;/a&gt;&amp;nbsp;&lt;br&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;</description>
      <pubDate>Sat, 23 May 2009 13:04:39 -0500</pubDate>
      <guid>http://wiki.futuretoby.com/Prototype_Inheritence_in_Python</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Prototype_Inheritence_in_Python</link>
    </item>
    <item>
      <title>Null in 10 Languages</title>
      <description>&lt;ul&gt;&lt;li&gt;Java, Javascript, C#: null&lt;/li&gt;&lt;li&gt;Ruby, Smalltalk, Lisp, OCaml: nil&lt;/li&gt;&lt;li&gt;Lisp: ()&lt;/li&gt;&lt;li&gt;Python: None&lt;/li&gt;&lt;li&gt;Haskell: Nothing&lt;/li&gt;&lt;li&gt;C: 0&lt;/li&gt;&lt;/ul&gt;</description>
      <pubDate>Mon, 11 May 2009 13:39:21 -0500</pubDate>
      <guid>http://wiki.futuretoby.com/Null_in_10_Languages</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Null_in_10_Languages</link>
    </item>
    <item>
      <title>Parameterizing Your Tests</title>
      <description>I use&#160;&lt;a href="http://seleniumhq.org/"&gt;Selenium&lt;/a&gt;&#160;at work to write browser tests. I use the Python bindings with Selenium Remote Control to drive the tests. Now, once you have written a test suite, it is not unreasonable to want to run the same set of tests over different browsers. Now that the browser space is getting interesting again, you'd better test your app on 5 or 6 browsers. So how do I write my tests once, and run them on different browsers? In the Python unittest framework, tests are written as classes that extend &lt;span class="Apple-style-span" style="font-style: italic;"&gt;unittest.TestCase&lt;/span&gt;. So, to parameterize them, you can can subclass the test dynamically and set the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;browser&lt;/span&gt;&#160;attribute onto it:&lt;pre&gt;import unittest

class TestPages(unittest.TestCase):
    def testPage(self):
        print("testing page on %s" % self.browser)

TestPagesOnFirefox = type('TestPagesOnFirefox', 
                                 (TestPages,), dict(browser='firefox'))

if __name__ == '__main__':
    unittest.main()&lt;br&gt;&lt;/pre&gt;&lt;div&gt;So, we are subclassing &lt;span class="Apple-style-span" style="font-style: italic;"&gt;TestPages&lt;/span&gt;&#160;calling it &lt;span class="Apple-style-span" style="font-style: italic;"&gt;TestPagesOnFirefox&lt;/span&gt;&#160;and at the same time&#160;setting its browser attribute to &lt;span class="Apple-style-span" style="font-style: italic;"&gt;'firefox'&lt;/span&gt;.&lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;div style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; "&gt;We run it and get this error:&lt;/div&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; font-family: monospace; font-size: 80%; background-color: rgb(238, 238, 238); padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; "&gt;AttributeError: 'TestPages' object has no attribute 'browser'&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;This is because &lt;span class="Apple-style-span" style="font-style: italic;"&gt;TestPages&lt;/span&gt;&#160;does not have the&#160;&lt;span class="Apple-style-span" style="font-style: italic;"&gt;browser&lt;/span&gt;&#160;property defined. What do we do? Let's erase it:&lt;/div&gt;&lt;pre&gt;del TestPages&lt;/pre&gt;&lt;div&gt;After that it runs okay and we get the output we want:&lt;/div&gt;&lt;pre&gt;testing page on firefox
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK&lt;br&gt;&lt;/pre&gt;&lt;div&gt;So we can generalize that and expand all the browsers you want to. We write an &lt;span class="Apple-style-span" style="font-style: italic;"&gt;expand_browsers&lt;/span&gt;&#160;function like so:&lt;/div&gt;&lt;pre&gt;def expand_browsers(gls, browsers=['firefox', 'ie6', 'ie7', 'safari', 'chrome', 'opera']):
    original_test_classes = filter(
        lambda o: isinstance(o, type) and issubclass(o, unittest.TestCase), 
        gls.values())
    
    for cls in original_test_classes:
        for browser in browsers:
            new_class = type('%sOn%s' % (cls.__name__, browser), (cls,), dict(browser=browser))
            gls[new_class.__name__] = new_class
        del gls[cls.__name__]&lt;br&gt;&lt;/pre&gt;&lt;div&gt;After you declare all you tests you call the function like so:&lt;/div&gt;&lt;pre&gt;expand_browsers(globals())&lt;br&gt;&lt;/pre&gt;&lt;div&gt;This goes through the namespace of your module and for each class that is a subclass of &lt;span class="Apple-style-span" style="font-style: italic;"&gt;unittest.TestCase&lt;/span&gt;(You can choose a different subclass as marker here if you want), it subclasses it and specifies the &lt;span class="Apple-style-span" style="font-style: italic;"&gt;browser&lt;/span&gt;&#160;property in it. After that, it erases the original testcase class so that it can't be found, like we did above.&lt;/div&gt;&lt;div&gt;Final complete example:&lt;/div&gt;&lt;pre&gt;import unittest

class TestPages(unittest.TestCase):
    def testPage(self):
        print("testing page on %s" % self.browser)

class TestMorePages(unittest.TestCase):
    def testPageTwo(self):
        print("testing page two on %s" % self.browser)

def expand_browsers(gls, browsers=['firefox', 'ie6', 'ie7', 'safari', 'chrome', 'opera']):
    original_test_classes = filter(
        lambda o: isinstance(o, type) and issubclass(o, unittest.TestCase), 
        gls.values())
    
    for cls in original_test_classes:
        for browser in browsers:
            new_class = type('%sOn%s' % (cls.__name__, browser), (cls,), dict(browser=browser))
            gls[new_class.__name__] = new_class
        del gls[cls.__name__]

expand_browsers(globals())

if __name__ == '__main__':
    unittest.main()&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Output:&lt;/div&gt;&lt;pre&gt;.testing page two on firefox
.testing page two on ie6
.testing page two on ie7
.testing page two on opera
.testing page two on safari
.testing page on chrome
.testing page on firefox
.testing page on ie6
.testing page on ie7
.testing page on opera
.testing page on safari
.
----------------------------------------------------------------------
Ran 12 tests in 0.000s

OK&lt;br&gt;&lt;/pre&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;Code examples also&#160;&lt;a href="http://github.com/airportyh/misc/tree/9e54618329e9eca9694dcebd60827dbbacd63fab/parameterized_tests"&gt;on github&lt;/a&gt;.&lt;/div&gt;</description>
      <pubDate>Wed, 11 Mar 2009 23:01:06 -0500</pubDate>
      <guid>http://wiki.futuretoby.com/Parameterizing_Your_Tests</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Parameterizing_Your_Tests</link>
    </item>
    <item>
      <title>goodday dot py</title>
      <description>Looking at rails and the&#160;&lt;a href="http://www.datejs.com"&gt;datejs library&lt;/a&gt;, I can't help but feel bummed that Python doesn't have an expressive date library like that. So I started one. I've put up my code on&#160;&lt;a href="http://code.google.com/p/goodday/"&gt;google code&lt;/a&gt;.&#160;</description>
      <pubDate>Thu, 22 Jan 2009 18:09:47 -0600</pubDate>
      <guid>http://wiki.futuretoby.com/goodday_dot_py</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/goodday_dot_py</link>
    </item>
    <item>
      <title>Auto-mixin in Python</title>
      <description>Python has multiple inheritence - a feature that's really handy because it allows the programing idiom called &lt;span class="Apple-style-span" style="font-style: italic;"&gt;mixins&lt;/span&gt;&#160;- where you write a a bunch of methods on a "mixin" class and then later on attaching all of those methods onto another class simply by mixin-it-in. In Python, the process of mixin-it-in is simply to add it to the parent list of the class:&lt;div&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; font-family: monospace; font-size: 80%; background-color: rgb(238, 238, 238); padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; "&gt;class MyObject(MyParent, MyMixin):&lt;/pre&gt;&lt;pre style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; font-family: monospace; font-size: 80%; background-color: rgb(238, 238, 238); padding-top: 0.2em; padding-right: 0.8em; padding-bottom: 0.2em; padding-left: 0.8em; "&gt;   ...&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;In Ruby, you can automatically mix in a mixin programmatically because the mix-it-in is done within the class definition, and because of its open classes. This is how the rails helpers are automatically found in a directory and mixed into the controllers for example.&lt;/div&gt;&lt;div&gt;How would you do this in Python? Let's say we simplify the problem to this: For a given Controller subclass named ProductController, for example, if there exists a helper class by naming convention: ProductControllerHelper, then we mix it in. Here's my solution:&lt;/div&gt;&lt;pre&gt;class Meta(type):
    def __new__(cls, name, bases, dct):
        helper_mixin = globals().get('%sHelper' % name)
        if helper_mixin:
            bases = list(bases)
            bases.append(helper_mixin)
            return type.__new__(cls, name, tuple(bases), dct)
        else:
            return type.__new__(cls, name, bases, dct)
        
class Controller(object):
    __metaclass__ = Meta
        
class ProductControllerHelper(object):
    def method1(self):
        print "method1 invoked"
        
class ProductController(Controller):
    def index(self):
        self.method1()
        
        
if __name__ == '__main__':
    ProductController().index()&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Output:&lt;/div&gt;&lt;pre&gt;method1 invoked&lt;br&gt;&lt;/pre&gt;&lt;div&gt;It worked!&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;But! We are not done. What if what you want to mix in depends on how you configure the class inside the class definition? In my case, I wanted to mix in a bunch of classes when I write a DSL-like declaration like this:&lt;/div&gt;&lt;pre&gt;class MyTestCase(TestCase):
    all = fixture(SeleniumRCServer, BrowserSession, DBData, Login)
    each = fixture(AddDelivery)&lt;br&gt;&lt;/pre&gt;&lt;pre&gt;    ...&lt;/pre&gt;&lt;div&gt;This is for a testing framework I am working on. I have a test case, and I want to specify its test context(fixtures) in the manner shown. Each object in the fixture(..) definition is a mixin. So I want to mix them all into MyTestCase.&lt;/div&gt;&lt;div&gt;This case is harder than the previous case because when __new__ is invoked, the class definition hasn't been processed yet, and therefore you won't have access to the class attributes &lt;span class="Apple-style-span" style="font-style: italic;"&gt;all &lt;/span&gt;and &lt;span class="Apple-style-span" style="font-style: italic;"&gt;each&lt;/span&gt;. The hack I came up with is this:&lt;/div&gt;&lt;pre&gt;class TestCaseMetaClass(type):
    def __init__(cls, name, bases, dct):
        if len(bases) == 1 and bases[0] != unittest.TestCase:
            bases = list(bases)
            bases.extend(cls.all)
            bases.extend(cls.each)
            cls.__real__ = type(name, tuple(bases), dct)
        else:
            type.__init__(name, bases, dct)
        
    def __call__(cls, *params, **kws):
        if hasattr(cls, '__real__'):
            return cls.__real__(*params, **kws)
        else:
            return type.__call__(cls, *params, **kws)
            
class TestCase(unittest.TestCase):
    __metaclass__ = TestCaseMetaClass&lt;br&gt;&lt;/pre&gt;&lt;div&gt;Basically, I first override __init__ of the metaclass(rather than __new__) in order to record what was declared in &lt;span class="Apple-style-span" style="font-style: italic;"&gt;all &lt;/span&gt;and &lt;span class="Apple-style-span" style="font-style: italic;"&gt;each&lt;/span&gt;, and create a new class on the fly mixing in all the mixins defined in the fixture(..) definitions. We store that class in an attribute __real__ attached to the class. Then we override __call__ for the metaclass to return an instance of the class held in the __real__ attribute instead of the actual class.&#160;Oh yes, this is really ugly, but it worked, at least for what I was doing. If you can write to a classes' __bases__ attribute(which defines the parents of the class), then this would be much easier, but I haven't figured out how to do it if it can be done at all. But because of this limitation, it looks unlikely you can do something like Ruby's&#160;&lt;a href="http://www.somethingnimble.com/bliki/mixology"&gt;mixology&lt;/a&gt;&#160;in Python.&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;U&lt;span class="Apple-style-span" style="font-style: italic;"&gt;pdate: the better solution to the second part is found:&lt;/span&gt;&lt;/div&gt;&lt;pre&gt;class Meta2(type):
    def __new__(cls, name, bases, dct):
        mixins = []
        all = dct.get('all')
        if all:
            mixins.extend(all)
        each = dct.get('each')
        if each:
            mixins.extend(each)
        bases = list(bases)
        bases.extend(mixins)
        return type.__new__(cls, name, tuple(bases), dct)
        
class TestCase(object):
    __metaclass__ = Meta2
    
class Fixture1(object):
    def method2(self):
        print "method2 invoked"
    
class Fixture2(object):
    def method3(self):
        print "method3 invoked"
        
class BlahBlahTest(TestCase):
    all = [Fixture1]
    each = [Fixture2]
    def blah_test(self):
        self.method2()
        self.method3()&lt;br&gt;&lt;/pre&gt;</description>
      <pubDate>Sun, 18 Jan 2009 00:03:16 -0600</pubDate>
      <guid>http://wiki.futuretoby.com/Auto-mixin_in_Python</guid>
      <author>toby ho</author>
      <link>http://wiki.futuretoby.com/Auto-mixin_in_Python</link>
    </item>
  </channel>
</rss>

