Speak and Shout

Tuesday, October 30, 2007

doctest with Python

At home I'm translating some C++ code to Python for doing 3-D math with vectors and matrices. (Yes, I know about NumPy -- I have my reasons.) Matrix math requires care to get all the indices right, and it's a good application for writing tests to make sure I've done things correctly.

About the same time as I started this project, I saw the following response from Fredrik Lundh (effbot) to a comment on Reddit:

>what was I thinking using self.assertEqual() in Python?!
Yeah, what were you thinking? Here's how it's spelled in Python, when using the One True Testing Tool (wink):
>>> foo.bar
3
(where all you actually typed was foo.bar; the rest is just good old cut and paste).

Of course, Fredrik here is referring to the doctest module. I'd seen Peter Norvig use it before in some of his Python code, and I should've paid attention then. Fredrik's comment gave me the push to finally try it. I found that it fits my style of Python coding very naturally, since I typically shake down my code at the REPL as I go. I cut and paste my interactions at the prompt into my class, and I've got some tests up and running quickly. The nice thing is that I'm helping to document my code (inline) as I go, which is a second advantage of doctest. I've never been that enamored with writing a separate test class like I've tried with the unittest library, for instance.

Good stuff. Thanks, Fredrik.

4 Comments:

  • This post has been removed by the author.

    By Blogger Jay Parlar, At 1:44 PM  

  • I've always felt that discovering and understanding the doctest module is one of the most important steps to understanding what "Pythonic" really means.

    By Blogger Jay Parlar, At 1:47 PM  

  • Always something to learn. Alex Martelli kinda puts down doctest in favor of unittest in "Python in a Nutshell", which is why I always bypassed it. But unittest is so old & heavy that I'd never use it. (Jonathan Ellis comments "does anyone still use that old module anymore?") I think it's important to find a testing style that fits how you work.

    By Blogger Brandon Corfman, At 3:24 PM  

  • Hi Brandon,

    You might want to look at Game Objects for your vector / matrix needs.

    http://code.google.com/p/gameobjects/

    By Blogger Will, At 6:46 PM  

Post a Comment



<< Home