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.

9 of 221 comments (clear)

  1. I love python by paRcat · · Score: 3, Insightful

    There are those out there that hate any language that allows spaces to effect it's running...

    But Python just rocks. Throw pySQL, wxPython and Twisted into the mix, and you can have a full blown server with gui front-end that is just as stable as any other. I have a server that I wrote for wireless devices performing a few hundred SQL queries/changes and file writes per hour, and the speed is surprisingly very good for a language most people refer to as a 'script'.

    Not to mention, the tab requirement makes reading the code so easy. You just know where functions begin and end without having to deal with {'s and }'s.

  2. Perl comparisons by goombah99 · · Score: 3, Insightful
    What I would like to have would be a merger of the perl and python cook books. I know my own understanding of perl exploded when I discovered the perl cookbook. I am now convinced that understanding a languages idioms is the secret to fluency.

    It would be very instructive to me to be able to see how the two languages handle each other's idioms. I have my brain wrapped around perl and when I try to think in python I get frustrated cause things I think should be simple aren't. Of course the reverse would be true if I knew python better (I guess).

    At present I think my python programming is too formal, like someone who just learned say french trying to speak it and saying "To The beloved person who bore me onto this earth; please to be informed that I have translocated my corpus into the domicale that lies here" instead of just saying "mom, I'm home".

    --
    Some drink at the fountain of knowledge. Others just gargle.
    1. Re:Perl comparisons by goombah99 · · Score: 2, Insightful
      Have not read that one. However I have seen similar concepts on line like "python for perl programmers." And generally these are not filled with examples of pithy worked translations. THe cook book contains the true idioms of a language hence i'd like to see a true cookbook-cookbook cookoff.

      for example, consider an indexed sort. in both perl and python you could do this by writing a loop to add an index field to each value then sort it then loop to gather the ordered indices. The only difference is the loops and indexing and sorting would have different grammar.

      But in perl one would probably instead do a map-sort-map idiom on a single line operation. And in python I suspect there is probably some simmilar idiom using iterators.

      its the idioms, not the formal grmammar crossovers that are important to learning to learning a new language.

      --
      Some drink at the fountain of knowledge. Others just gargle.
  3. Buying from evil companies by yerricde · · Score: 2, Insightful

    Get it from Amazon for [$3.99 cheaper]

    And fund enforcement of a patent that should never have been granted. If you want to preserve balance in the Force, you have to give to EFF every time you give to a company that employs "evil" practices with respect to statutory monopolies. That's why I don't buy more than $65 a year from Disney, Time Warner, Universal, or the other big nine copyright companies, and that's also why I don't buy from Amazon or use Unisys products.

    --
    Will I retire or break 10K?
  4. Re:Try Ruby! by Twylite · · Score: 1, Insightful

    Looks like a classic example of bad syntax to me. I don't know Ruby, or Python ... but I do know when I see a language which does not have an intuitive syntax or grammar.

    While the "5.times" is rather obvious, if not leaving one wondering why a "." is needed, |n| would be read by your average degreed professional developer as "the absolute value of n", given its visual similarity to the well known and standard mathematical notation for this operation. Which of course makes "|n| puts n" a rather illogical statement, and a best "take the absolute value of n and then print it".

    Terse is good only if it is understandable ... not if it is readable.

    --
    i-name =twylite [http://public.xdi.org/=twylite], see idcommons.net
  5. 1.5.2 code still works with 2.2 by Anonymous Coward · · Score: 1, Insightful

    As demonstrated throughout the Cookbook all of the code snippets the code for 1.5.2 will work with 2.2. I think its unfair to say that the Cookbook will be deprecated or unusable in 2 years. The recipes are more than just code examples they explain the authors intent. As Python marches to world domination we will pick up interfaces, and a few other language features that will make it - the obvious general purpose language of choice. These features will not
    get in the way of people picking up the cookbook. Or make old code not work. It will
    merely make new code better.

  6. Re:HTML Email by dvdeug · · Score: 3, Insightful

    HTML email is not just for spammers.

    No; it's also for people who want me to want a half hour to get my mail over my modem, so I can get the exact same message but with lots of HTML tags. (And invariablly lots of HTML tags - it never bears any resemblence to clean hand-written HTML.)

    The ability to send HTML forms to employees is a boon among other benefits.

    And what happens when you need to make a change to that form? Why not just stick it your own private webspace?

    Maybe you've never shared the joy of sending an HTML birthday card to your child or parent.

    Ah, yes; the wonderous feeling of "you crossed my mind, but I couldn't be bothered to walk to the store for a _real_ birthday card".

    It's a little more valid, but it's still something that can be done via web.

    The ability to communicate with the richness of HTML expression

    To be or not to be; that is the question. Whether 'tis greater to suffer the slings and arrows of outrageous fortunes, or by dying, end them. . . .

    I fail to see how this could be made richer by adding HTML. In general, just straight plain text is an extraordinarily powerful medium for communication. Frequently, HTML seems to be used as a means to doodle on the email, rather then add any information or emotional empact.

  7. Slashdot topics by fm6 · · Score: 5, Insightful
    Slashdot icons are just designators for Slashdot topics, and these desperately need an overhaul. There are topics for companies that no longer exist (Digital, Compaq, LinuxCare; Be should probably be renamed "BeOS"); topics that are extremely low volume and should really be folded into other topics (Comdex, E+, Englightenment), topics that are just plain redundant (Bugs, Linux Business), topics that we need only because they're part of a more general topic we don't have (we have America Online, but no ISP topic; topics for various Desktops, but no general Desktop topic; topics for specific Linux distros, but no Distro topic). And why on earth do we have ten specialized Apple topics?

    Rather than a new topic for Python, I'd rather see a Scripting topic. So, yeah, that means no cute Python icon, but it does put all the scripting issues in one place for people to select or ignore.

  8. Re:An indictment of the Python programming languag by Da+VinMan · · Score: 4, Insightful

    Aside from the point about lack of declaration of variables, you're points against Python all reduce down to syntax issues.

    It's a good thing you posted AC. I wouldn't want to take credit for that dreck either.

    Oh, and if Python were only two years old, then I wouldn't have been able to do the Python project I did for a client when I did.

    Have you even used Python? I didn't think so. I guess that if you want to be cynical and condescending about a language just because you're a self-appointed language guru, then please go ahead. But I think we would all prefer that you keep your opinion under wraps until it is informed and rational.

    --
    Please mod this post only if you think others should/n't read this. I have enough ego^H^H^Hkarma. Thanks!