Slashdot Mirror


The Python Cookbook

Nice2Cats writes "Python is something of a programmer's dream and an author's nightmare. What started life as a scripting tool for the Amoeba operating system has matured into a full-blown programming language with such speed that every book seems to be outdated in a year or two. To make matters worse for publishers, the crew around Python's creator Guido van Rossum keeps adding higher-level constructs such as iterators with every new release, reducing reams of code to single-line idioms at half-year intervals. Because not everybody has been able to keep up -- RedHat 7.3 infamously still ships with version 1.5.2 as the default, while SuSE 8.0 is hanging in there with version 2.2 -- authors are forced to cover stone age variants as well as modern forms. Python is cross-platform (Unix/Linux, Mac, Microsoft), has two underlying languages (C for Python, Java for Jython) and works with various GUIs (Tkinter, wxWindows, Qt, GTK, curses, Swing). Given this breadth of material, the idea of writing that most fragmented form of a programming book, a 'Cookbook,' seems as crazy as, say, nailing a dead parrot to its perch." Read Nice2Cats's review below of The Python Cookbook to see how well O'Reilly deals with dead parrots. The Python Cookbook author Alex Martelli and David Ascher pages 574 publisher O'Reilly rating 8 reviewer Nice2Cats ISBN 0596001673 summary A recommended book for the language with no Slashdot icon.

Beautiful plumage. O'Reilly, fortunately, has all kinds of experience with animals.

The Python Cookbook consists of seventeen chapters that contain between eight and twenty-six individual recipes. Chapters and recipes are roughly ordered by increasing complexity, length, and required background knowledge, starting with the simple "Swapping Values Without Using a Temporary Variable" and ending with the complete module "Parsing a String into a Date/Time Object Portably." The chapters are mostly organized by subject -- "Text," "Files," "Object-Orientated Programming," "User Interfaces" -- but also include "Python Shortcuts" and "System Administration." The background required varies: Whereas the chapter on "Text" starts off with Fred L. Drake reviewing the most basic string operations such as slicing and concatenation, Paul F. Dubois can only sketch the core concepts of lexing and parsing in "Programs About Programs."

This of course is a hallmark of all cookbooks, programming- or food-wise: Nobody will like everything, but everybody will like something. The worst fragmentation occurs, as expected, between examples of Python 1.5.2 and Python 2.2. Most recipes give preference to one version, and then point out how the problem could have been solved in the other version. This is more useful than the code that was written for all versions, because it gives a deeper insight into the changes that Python has gone through. The result is that after a few chapters, you start wondering why anybody in their right mind would keep using Python 1.5.2 instead of 2.2.* with its iterators, list comprehensions, new classes, and expanded module library.

Martelli and Ascher have done a good job balancing the different forms. Only one chapter struck me as lopsided: "System Administration", where ten of the sixteen recipes are Windows-only. Even though there is a good reason for this -- Microsoft's native administration tools just aren't like those provided with Unix -- the editors might want to rethink the selection of recipes in this chapter for future editions.

Generally helpful. The "Python Cookbook" has helped me in three ways. First, I found quite a lot of the examples themselves, especially those in the chapters "Python Shortcuts" and "Object-Orientated Programming" useful for everyday work. Second, reading more than 500 pages of peer-reviewed and well-commented code gave me a greater feeling for common idioms and constructs that are rare in this clarity in wild-type code. However, the book is strongest when more general principles of "Pythonic" programming are discussed, for example when Martelli demonstrates the merits of the "Look Before You Leap," "Easier to Ask Forgiveness than Permission," and "Homogenize Different Cases" methods.

My favorite recipe is Sebastien Keim's "Implementing a Ring Buffer," where an object carries a class deep in its bowels, and changes into this class in a rather cool Dr.-Jekyll-to-Mr.-Hyde transformation on the fly. The one recipe I found downright evil was "Sending HTML Mail," which should have been implemented as "Turning HTML Mail into Plain Text" with a note on how people who send HTML mail are going to be the first against the wall when the revolution comes. The best quote in the book comes from Tim Peters: "We read Knuth so you don't have to" -- Python's promise of programming power for the people, expressed in (dare I say it) a nutshell.

Conclusion:

I can recommend the "Python Cookbook" wholeheartedly to anyone who has passed into the advanced stage of language learning and is willing to actually sit down and work through the code. Anybody who is looking for a deeper understanding of Python, solutions to common coding problems, or starting points for their own projects will also profit. This book should have RedHat customers hammering at the gates of Raleigh, demanding the power of iterators and list comprehensions that their SuSE counterparts already enjoy by default; it demonstrates the superiority of Python 2.2.* over 1.5.2 in great detail.

Because of this, however, my guess is that 2.2.* will quickly replace 1.5.2, turning large parts of this book into historical footnotes in two years at the latest. This is no fault of O'Reilly's, but rather a current fact of Python life. The editors have done a good job of nailing the parrot, and until this Pythonic Norwegian Blue does the inevitable backflip, it should give its owner much pleasure.

You can purchase The Python Cookbook from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

12 of 221 comments (clear)

  1. Debian also has 2.2 by psgalbraith · · Score: 3, Informative

    RedHat 7.3 infamously still ships with version 1.5.2 as the default, while SuSE 8.0 is hanging in there with version 2.2

    Debian unstable also has 2.2 as the default python, although the stable release has 2.1. But with the huge number of packages which depend on it, it takes a while to migrate all of them. So testing still has 2.1.

  2. Re:Swapping Values Without Using a Temporary Varia by Anonymous Coward · · Score: 5, Informative

    a,b = b,a

  3. Re:asdf by Phoukka · · Score: 4, Informative

    Much more to the point, Red Hat 7.3 has 1.5.2 as "python", but has 2.1 (IIRC) as "python2". And Red Hat 8 has 2.2.1 as its "python". And, as you said, it is eminently possible to download and compile the latest version, though you do have to be careful that you link in 2.2.x as "python2" rather than "python" on Red Hat 7.3, or many of the system apps break (up2date comes to mind...).

  4. 2.2 for RedHat by redfenix · · Score: 5, Informative

    This book should have RedHat customers hammering at the gates of Raleigh, demanding the power of iterators and list comprehensions that their SuSE counterparts already enjoy by default; it demonstrates the superiority of Python 2.2.* over 1.5.2 in great detail.

    Of course, installing a new version of Python in RedHat is pretty painless, download the rpm and install it. You can find them here.

    --
    "It's a very tangled subsystem." --Windows kernel guru
    1. Re:2.2 for RedHat by Linux_ho · · Score: 3, Informative

      RedHat 8.0 installs Python 2.2.1 by default.

      --
      include $sig;
      1;
  5. Re:Swapping Values Without Using a Temporary Varia by spakka · · Score: 1, Informative

    No, it isn't.

  6. Re:Perl comparisons by snowbike · · Score: 2, Informative

    Check out Perl to Python Migration by Martin Brown. Sure, it isn't O'Reilly, and it doesn't have "cookbook" in the title, but I've found it a good start for the type of thing you are asking about.

  7. Re:Perl comparisons - see PLEAC by Anonymous Coward · · Score: 1, Informative

    This is almost exactly what you want (assuming you have the Perl Cookbook in hand):

    http://pleac.sourceforge.net/pleac_python/t1.htm l

  8. perl/python phrasebook by mcc · · Score: 5, Informative

    Try this site.. it's basically a "phrasebook" that shows common tasks being done in both perl and python. It's a great introduction to the language, and it helps a lot in terms of getting the python-idiom-y ways to do lots of commonthings embedded into your head.

    It isn't *very* long, and doesn't go too deep, and the formatting's not great, but it's a quick read, and if it doesn't fit your needs there's always that book Snowbike recommended.

    At present I think my python programming is too formal

    The catch about the funkiness of python's syntax is not that it demands formalism; it's just that it demands you will do only one thing per line. It's kind of hard to get yourself thinking this way, and it's really irritating to write code this way (i never write python without pining for a ?: construct, a single-line version of "except", or a less-crippled lambda construct).

    The thing is, though, that obeying python's rule basically comes down to seperating each expression into unnecessary variables, and mercilessly abstracting all those potentially-repeated 'common tasks' that somehow always seem to wind up taking five lines in python into functions. However, i find when i write perl, most of the time i spend revising code is spent going back and doing the above two things-- splitting overly-complex expressions into subvariables, pulling out bits of code and making them subexpressions. Python just forces you to do these things ahead of time, and you benefit greatly in the long run. (Whether that's worth all the irritation, though, i don't know :))

  9. Re:Don't click on Slashdots book link by Gramie2 · · Score: 2, Informative

    Or $24.50 from www.bookpool.com, which is almost always better than other online bookstores, although I'm not sure how it does once shipping is factored in.

  10. Language Development Speed by Bouncings · · Score: 4, Informative
    Actually, the rapid change in the language is pretty new. For the longest time, 1.5.x was stable, and years before 1.4.x was mostly the same. Then, 1.6 happened. Python hit some kind of critical mass where Guido decided to more or less open the flood gates of third party suggestions (called PEP's in Pythonlore). Another key factor was the rapid increase of XML libraries and concerns, as well as other quickly changing technologies.

    The author of this article doesn't mention it, but many Python programmers are upset with the rapid changes in the language, and it is very contrary to Python's history and philosophy. It looks like for now though, Python is slowing back down after implementing a new system of object orientation that really implements each variable/function/whatnot as an object. 2.2, hopefully, is here to stay for a while.

    --
    -- Ken Kinder ken@_nospam_kenkinder.com http://kenkinder.com/
  11. Re:Try Ruby! by Hornsby · · Score: 4, Informative

    The "." is needed because 5 is an object of type Fixnum. times is a method available to Fixnum objects. I used that example to demonstrate that EVERYTHING in Ruby is an object. For instance, you can do the following:

    "hello world".upcase
    "HELLO WORLD"

    Not to mention method cascading

    "hello world".upcase.reverse
    "DLROW OLLEH"

    Once you get used to having these features, it's hard to go back(to Perl that is...). There are a number of other very nice features as well. Iterators for example(which Perl 6 is going to include).

    list = ["foo", "bar", "car"]
    list.each do |elem|
    # do something with elem
    end

    For a quick walkthrough of the languages features, go here: http://rubycentral.com/book/intro.html

    I do know when I see a language which does not have an intuitive syntax or grammar.

    And what language does? Any new language requires an adjustment period. The important thing is consistency once you get over the initial learning curve. Lisp doesn't necessarily have an intuitive syntax either; however, few would argue that it's not a powerful language. The consistency of having everything represented as a list makes it's syntax extremely simple.

    --
    A musician without the RIAA, is like a fish without a bicycle.