Forgot your password?
typodupeerror
Programming Books Media Book Reviews IT Technology

Python in a Nutshell 246

Ursus Maximus contributes this review of Python in a Nutshell, writing "Perhaps the best book about Python ever written, this is the perfect capstone to anyone's library of Pythonic books, and also the perfect introduction to Python for anyone well versed in other programming languages. For newbies to programming, this would still be a good second book after a good introductory book on Python, such as Learning Python by Mark Lutz." Read on for the rest of his review.
Python in a Nutshell
author Alex Martelli
pages 636 pages
publisher O'Reilly
rating Excellent, superb, 5 stars
reviewer Ron Stephens
ISBN 0596001886
summary Complete reference book for the Python programming language

Written by my favorite author and Pythonista, Alex Martelli, this book manages to fill three roles in extremely pleasing fashion. First and foremost to me, it is a great read, straight through. Mr. Martelli's prose is always sparkling and always keeps the reader interested. No matter how many Python books you have read, you will learn some nuances from this book, and it is about the best review of the whole Pythonic subject matter that I can imagine. While there is absolutely no fluff whatsoever in these 636 pages, it still makes for rather easy reading because the explanations are so clearly thought out and explored as to lead one gently to understanding, without in any way being verbose. It is obvious that Alex Martelli took his time and put in sufficient thought, effort, and intellectual elbow-grease to make this work a classic for all time.

Secondly, this book is the ultimate Pythonic reference book, the best fit to this role I have yet seen. You will keep this book in the most cherished spot on your book shelf, or else right at your side on your computer desk, because you can almost instantly find any topic on which you need to brush up, in the midst of a programming project.

Third, Python in a Nutshell is the most up-to-date book on Python (as of April 2003) and includes the best and most complete expositions yet on the new features introduced in Python 2.2 and 2.3. These topics are not only covered in depth, they are integrated into the text in their proper positions and relationships to the language as a whole. They are explained better here than I have seen anywhere else, so much so as to make them not only understandable to me (a duffer), but indeed so that they appear seamlessly Pythonic, as if they had been a part of the language since version 1.0. Topics explored in depth include new style classes, static methods, class methods, nested scopes, iterators, generators, and new style division. List comprehensions are made not only comprehensible but indeed intuitive.

The book is surprisingly complete. It covers the core language as well as the most popular libraries and extension modules. It is difficult to choose any one portion of the book to highlight for extra praise, as all topics are treated so well. It is a complete book, the new definitive book about Python.

Everything about this book speaks of quality. In addition to the top notch writing and editing, O'Reilly really did the right thing and published this book printed on the highest quality paper, paper so thin that the 636 pages are encompassed in a book much thinner than one would expect for such a size, but strong enough to resist wear and tear. The text is most pleasing to the eye. Holding the book, and turning its pages, gives one a feeling of satisfaction.

Any job worth doing is worth doing well. Alex Martelli and O'Reilly have done justice to a topic dear to our hearts, the Python programming language. Perhaps, in years to come, the passage of time may make this book to be no longer the most up-to-date reference on the newest features added to Python. But time can not erase the quality craftsmanship and the shear joy of reading such a well thought out masterpiece of Pythonic literature.


You can purchase Python in a Nutshell from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page. Ron Stephens would also like you to check out Python City, with "27+ reviews of books about Python. 67+ links to online tutorials about Python and related subjects Daily newsfeed of Pythonic web articles, new sourceforge projects, etc."

This discussion has been archived. No new comments can be posted.

Python in a Nutshell

Comments Filter:
  • Very Pythonic (Score:3, Informative)

    by Limburgher ( 523006 ) on Wednesday April 16, 2003 @11:55AM (#5744181) Homepage Journal
    I liked this review. Sparkling, fluffless and pythonic. Adjectival as well.

    Also, in response to an earlier post, the fries are spelt Julienne. And are damn tasty.

  • by Ed Bailey ( 1912 ) on Wednesday April 16, 2003 @11:55AM (#5744184) Homepage
    ...I found New Riders Python Essential Reference to be a far better introduction to the language. I eagerly waited for Python in a Nutshell to come out, but I found I kept gravitating back to my copy of Essential Reference (the second edition, btw).

    I am normally never disappointed with an O'Reilly book, but I was in this case. I hope it's not the start of a trend for them...
  • by hfastedge ( 542013 ) on Wednesday April 16, 2003 @12:00PM (#5744217) Homepage Journal
    Slashdot accepted something from python by me, and here it is again as I think its relevant. Python is just great :-)

    http://slashdot.org/articles/03/03/11/1817203.shtm l [slashdot.org]

    hfastedge [wikipedia.org] writes "Ok, now that 2 perl conferences have been mentioned, I've been brought over the edge. Python [python.org] is a language that is just as old, and arguably [www.amk.ca] better from: most importantly a uniform standard of readability (enforced by using whitespace [wikipedia.org] to delimit blocks (instead of {}), by avoiding overuse of cryptic symbols, and by a culture [python.org] that strives to keep innovations as "pythonic"), and a rich [python.org] development [python.net] community. Anyway, normally, there are Python events [python.org]

    in Europe, and a trail at O'Reilly's OSCON. But now, there is a far
    cheaper event taking place on March 24-28 in Washington DC: http://python.org/pycon/ [python.org].



    Examples of Python in action: , 1 [google.com], 2 [pythonware.com], 3 [oreillynet.com], 4 [intelligen...rprise.com], 5 [scipy.com], 6 [onlamp.com], 7 [pygame.org]"

  • by liquidsin ( 398151 ) on Wednesday April 16, 2003 @12:03PM (#5744234) Homepage
    "two peanuts were walking down the street and one was assorted"

    I believe you're going for "one was assaulted" (a salted...*zing*)
  • Pythonic (Score:4, Informative)

    by FuzzyDaddy ( 584528 ) on Wednesday April 16, 2003 @12:08PM (#5744265) Journal
    is a word often used in the Python community to describe something that fits well with the Python design philosophy.
  • by john_roth ( 595710 ) on Wednesday April 16, 2003 @12:21PM (#5744347)
    But the problem is that Python suffers from a lot of Perl's problems and adds a few of its own: you can't implement it in itself, it has no strong typing (even Perl's use strict is ridiculously better), an OO system with no support for data hiding, etc. etc

    Actually, one of these is being worked on: There's an active project to write Python in itself. I believe they're taking the same tack as Squeak.

    John Roth
  • by Anonymous Coward on Wednesday April 16, 2003 @12:22PM (#5744359)
    I would call you a karma whore if you weren't AC. If anybody would like to see the unplagiarized version of this post and the thread it came from Here it is [perl.org].

  • by avdi ( 66548 ) on Wednesday April 16, 2003 @12:23PM (#5744363) Homepage
    By far the best programmer's introduction to Python (in fact, one of the best programmer's intros to any language) I've ever read is Mark Pilgrim [diveintomark.org]'s Dive Into Python [diveintopython.org], a free online book.
  • by spareparts ( 398231 ) <joshhoyt AT gmail DOT com> on Wednesday April 16, 2003 @12:26PM (#5744378) Homepage
    The exception mechanism provides a way for you to break out of multiple loops if there is not already an elegant way to express your loop. Also, the else clause for loops can be useful in some cases.

    Objects are already passed by reference. You can't change strings because they are an immutable type. If you need references, you can use the weakref module, or create your own wrapper class (delegating accesses to the underlying object).

    you can define named functions in-line, that work as closures (i. e. using variables from the declaration scope). I've been using Python 2.3, so the change from 2.2->2.3 may have been the change that made this usable. In case I wasn't clear:
    def curry(f, arg):
    def curried(f, *args):
    return f(arg, *args)

    return curried
    do/while is missing. That sucks.
  • by mzs ( 595629 ) on Wednesday April 16, 2003 @12:26PM (#5744381)
    The book I both used to learn python and continue to go back to as a very useful, detailed, and fairly complete reference is "Python Essential Reference" by the creator of SWIG David Beazley. (If you ever wanted to mix C, java, python, perl, tcl go to http://www.swig.org/ sometime.) There is a newer second edition out now but the orignial was laid out as a short tutorial chapter to get started in python, then several short chapters about language details (lexical matters, types, operators, control flow, functions, classes, modules, and I/O), and the typical chaper about installation and site issues. This first section is less than 90 pages, fantastic for people already familiar with programming that want to quickly learn the syntax of python so they can get immediately started with python coding.

    Then there is Appendix A which gives a short description of all built in functions and exceptions followed by concise descriptions of most of the standard python modules circa 1.5.2 (the newer edition is probably 2.0-ish) that are detailed enough to use as reference. Appendix A also has short examples and detailed explanations with background information where it is beneficial in the descriptions. The module reference is divided into topical sections such as string modules, networking modules, and threading modules and modules with related or complimentary functionality are cross referenced.

    Finally there is a short Appendix B that explains how easy it is to extend python with C modules and even a bit of how to embed the python interpretter into your own programs and libraries!

    Most importantly the book is only 274 pages and has a very useful index when you want to use it as a reference. Together with the online documentation at http://www.python.org/doc/ this book is invaluable to me.
  • by Kidbro ( 80868 ) on Wednesday April 16, 2003 @12:27PM (#5744385)
    - Python has 'break' and 'continue' like C. But these only affect the innermost loop. Is there a way to break out of an enclosing loop? (In Perl you can label a loop and then say 'next LABEL', etc.)

    Usually solved by a try/except clause when needed - which it seldom is.

    - How can I pass a variable by reference?

    EVERYTHING is a reference. You pass nothing but references. If you call foo(bar), foo will have a reference to the exact same object as bar pointed to. The fact that you can not modify a string passed to a function is because strings are immutable.

    - Python advertises its support for first-class functions, but I can't seem to get closures to work.

    Can't really comment on this I'm afraid. lambdas are very simple, yes. You can define functions within functions - and they will (in 2.2.1) be able to read from, but not write to the name space of the enclosing function, IIRC.

    - Is there a do/while statement in Python?

    No. The Python philosophy is usually "Have one way to do it." do/while doesn't really solve problems a simple while clause doesn't solve. Keep it simple.
  • by Frater 219 ( 1455 ) on Wednesday April 16, 2003 @12:31PM (#5744404) Journal
    Python has 'break' and 'continue' like C. But these only affect the innermost loop. Is there a way to break out of an enclosing loop? (In Perl you can label a loop and then say 'next LABEL', etc.)

    Like Java and Lisp -- and unlike Perl -- Python has exception handling. The structured way to get out of an inner loop is the same as the structured way to get out of a deeply nested function call: raise an exception, and trap it at the higher level where you want to "go to".

    How can I pass a variable by reference? For example, to take a reference to a string, pass it to a function and have that function modify the string passed in. More generally, is there a way to store references?

    In Python, everything is a reference, but strings are immutable objects. There's no such thing as "modifying the string passed in" -- all the built-in string functions return a new string. However, for mutable types such as lists and dictionaries, functions can certainly modify their arguments, as in this example:

    def foo(lst): lst.append("beer")
    y = ["wine"]
    foo(y) # y is now ["wine", "beer"]

    Python advertises its support for first-class functions, but I can't seem to get closures to work. The 'lambda' keyword won't accept assignment or even sequencing inside the function body.

    Especially since I have some Scheme in my programming background, this is a quirk I find annoying about Python: lambda is underpowered. It's comparable to the old BASIC "DEF FN" in that it allows only expressions, not statements, in the lambda-body.

    However, you can do what you want by defining a function with a temporary name, using def, and returning it. (In Python it is perfectly valid to have function definitions inside other function definitions, and it does what you expect: defines functions whose names have local scope, but can be returned.) You can also create callable classes, which act like functions instead of object factories. There's an implementation of curry for instance in the Python Cookbook, which does this. Check it out. [activestate.com]

    Is there a do/while statement in Python? Plain 'while' is there but occasionally an 'at least once' loop is what you need. Is there an addon package or library for Python that provides a 'do' construct?

    There is neither a do/while nor a repeat/until in Python. Again this is something I don't agree with, but the argument is that this keeps the number of redundant keywords down. The convention is to use while loops and escape with break when necessary.

  • by Anonymous Coward on Wednesday April 16, 2003 @12:33PM (#5744418)
    > - Python has 'break' and 'continue' like C. But these only affect the innermost loop. Is there a way to break out of an enclosing loop?

    You'd use an exception.

    >- How can I pass a variable by reference?

    All variables are passed by reference.

    > For example, to take a reference to a string, pass it to a function and have that function modify the string passed in.

    Strings are immutable so they can't be changed. Your function would return a new string with the new value.

    > - Python advertises its support for first-class functions, but I can't seem to get closures to work.

    Closures with nested function definitely work. Don't use lambda's -- they're an admitted failed experiment.

    > - Is there a do/while statement in Python?

    No. Occasionally missed, "while True:" is a widely used idiom instead.

    Oh, and btw, Python can be written in itself, and it's plenty fast for "real CS". There are tons of free and commercial software written it it. It's niche are projects that want a competitive advantage and long term maintainability.
  • by tal197 ( 144614 ) on Wednesday April 16, 2003 @12:36PM (#5744440) Homepage Journal
    Python has 'break' and 'continue' like C. But these only affect the innermost loop. Is there a way to break out of an enclosing loop?
    Throw an exception and catch it whereever. Eg:
    try:
    __while ...
    ____while ...
    ______raise FinishLoop
    except FinishLoop: pass

    How can I pass a variable by reference? For example, to take a reference to a string, pass it to a function and have that function modify the string passed in.
    Everything is always passed by reference. You can't modify a string because strings are immutable.

    The 'lambda' keyword won't accept assignment or even sequencing inside the function body. So anonymous functions you might want to pass around can't do much beyond trivial operations.
    lambda is a short-hand for def. Use that if the body isn't a simple expression:

    def make_print(message):
    __def new_fn(): print message
    __return new_fn
    make_print('Hello')()

    Is there a do/while statement in Python?

    while 1:
    __# Stuff
    __if finished(): break

    Some python tutorials I wrote:

    Python for BASIC programmers [sourceforge.net]
    Writing GTK applications in python [sourceforge.net]

  • by Surak ( 18578 ) <surak&mailblocks,com> on Wednesday April 16, 2003 @12:37PM (#5744447) Homepage Journal
    I'd have to say that more than a few people [php.net] are using PHP. In fact, of the available Apache modules, guess which one is the most popular [securityspace.com]? (Hint: it's not PyApache or even mod_perl by a long shot)

  • by Anonymous Coward on Wednesday April 16, 2003 @12:53PM (#5744567)
    Learn your terminiology:

    Python has STRONG DYNAMIC typing.

    C has WEAK STATIC typing.

    Perl5 has WEAK DYNAMIC typing (Argh!)

    Common Lisp has STRONG DYNAMIC and OPTIONAL STRONG STATIC typing.

  • by frankie_guasch ( 164676 ) on Wednesday April 16, 2003 @12:55PM (#5744585)
    Like Java and Lisp -- and unlike Perl -- Python has exception handling.

    Perl has exception handling with die/eval. Here is an article [perl.com] about it.
  • by Anonymous Coward on Wednesday April 16, 2003 @12:57PM (#5744595)
    Cameron Laird: Book review: Python in a Nutshell [unixreview.com] "Cameron Laird reviews Alex Martelli's 'Python in a Nutshell' for UnixReview.com. Experienced, erudite author. Compelling topic. Proven format. What happens when you combine them? It depends. In book publishing, as with rock-and-roll bands and athletic teams, there are plenty of cases where apparent 'all-star' combinations have turned out badly. The fate of 'Python in a Nutshell' is happier, though. If you want to learn about Python, and can choose only one book to do so, take 'Python in a Nutshell'."

    Lifted whole cloth from Daily Python-URL [pythonware.com]

  • by thermostat42 ( 112272 ) on Wednesday April 16, 2003 @01:08PM (#5744668) Homepage
    range generates the entire sequence beforehand. xrange, OTOH, will generate them one by one.
    HTH
  • by Luke Skyewalker ( 585866 ) <skyewalkerluke@hotmail.com> on Wednesday April 16, 2003 @01:18PM (#5744736)
    other useful books:

    The Quick Python Book by Harms and McDonald
    This one covers a quite older version of python (1.5), but is a good tutorial nonetheless.
    Programming Python by Mark Lutz
    A very good book to see python in action.
    Python Standard Library by Fredrik Lundh
    A very good reference book for some things not covered by Python Essentials (ex htmllib)

    However, I would greatly avoid the Python Pocket Reference (also by Lutz) just because it doesn't have an index to modules...
  • by Anonymous Coward on Wednesday April 16, 2003 @02:15PM (#5745168)
    Conceptually, a for loop always iterates over the members of a sequence. range is just an example of generating a sequence. This is actually quite nice, because if you have a sequenence of lines in a file, you can do stuff like "for line in file:" and loop over them easily. You aren't stuck looping only over integers.

    As for your actual question: range does generate the entire list. xrange generates an object instead that calculates the items on the fly. Newer versions of python will be changing things (if they haven't already) so that range generates on the fly as well, and gets rid of the xrange object.

    Benchmarks have shown over time that xrange is not appreciably faster than range; you have to spend the time generating that number somewhere, either up front or one at a time. The only reason to use xrange is if you have a very large sequence to loop over, and can't afford the storage for the temporary list.
  • by Paul Komarek ( 794 ) <komarek.paul@gmail.com> on Wednesday April 16, 2003 @02:38PM (#5745376) Homepage
    I cannot agree with the reviewer that M. Lutz's O'Reilly "Python" book is good. I disliked this book nearly all the way through. It jumped around too much, used too many words, and had insufficient detail on more advanced topics. Given that the book is about three inches thick (from memory -- I gave away my copy), there's enough room for details on everything.

    I concur with other posters that the "Essential Reference" (white and red from New Riders, written by D. Beazley who did SWIG) is an awesome book. It is concise, making it a good reference. I wouldn't think it was a good book for those who have never programmed. If you have some programming experience, though, I expect you'll appreciate this book.

    The "Quick Python" book from Manning is nice, too. This was my wife's preferred book for learning Python. I've looked through it a bit, and it seems decently concise but with more explanation than "Essential Reference". I used its section on extending Python through C, and found it very useful. That section didn't have everything bit of reference that I needed for conversion specifiers, but their examples were dead-on what I needed to get started.

    I recently finished reading through "How to Think Like a Computer Scientist: Learning With Python" from Green Tea Press. This book is not a complete reference or guide for Python, nor will it be particularly 'useful' for people who have taken university-level programming and data structures classes. However, it seems to be an AWESOME book for people who don't yet program, or whose only experience is web programming or VB or Perl programming (I'm not saying those things are bad, but very often they don't encourage reasonable programming discipline and methodology). I write "it seems" only because I'm not a beginner or an instructor for intro to programming courses.

    This book ("How to Think...") is aimed at classroom use, so it doesn't include info about installing Python or starting the Python interpreter under Windows, etc. It does preach solid computer science. Parts of their approach seemed a bit unusual to me, compared to my more classical training, but after a few gripes I always was forced to conclude that their approach was valid and as concise and clear as it could be. The authors are aware of the book being used in high schools and community colleges. I expect that mature students, or any adult intrested in learning proper programming, would benefit from starting with this book.

    -Paul Komarek
  • by frehe ( 6916 ) on Wednesday April 16, 2003 @03:41PM (#5745981)

    If you need more speed than native Python provides, you can always write code in C and wrap it so it is callable from Python. The wrapping is really easy to do, once you have understood the general concepts involved in it. The product I currently work on has about 10000 lines of C code (crypto and networking) which is used this way, and it works perfectly. For more information about extending Python with C, see:

    Extending and Embedding the Python Interpreter [python.org]

    Python/C API Reference Manual [python.org]

  • by Fourier ( 60719 ) on Wednesday April 16, 2003 @04:10PM (#5746254) Journal
    I cannot agree with the reviewer that M. Lutz's O'Reilly "Python" book is good. I disliked this book nearly all the way through. It jumped around too much, used too many words, and had insufficient detail on more advanced topics. Given that the book is about three inches thick (from memory -- I gave away my copy), there's enough room for details on everything.


    Mark Lutz actually has two noteworthy Python books, "Programming Python" and "Learning Python."
    "Programming Python" would be the thick book you refer to; the author of the review recommends "Learning Python," a thin book for those just learning the language (or maybe still learning programming). It has been pretty well received.

I'm all for computer dating, but I wouldn't want one to marry my sister.

Working...