Python in a Nutshell
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."
"two peanuts were walking down the street and one was assorted"
I believe you're going for "one was assaulted" (a salted...*zing*)
do not read this line twice.
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
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.
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:do/while is missing. That sucks.
- 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.
May we live long and die out
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".
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:
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.
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.
> - 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.
Throw an exception and catch it whereever. Eg:
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:
Is there a do/while statement in Python?
Some python tutorials I wrote:
Python for BASIC programmers
Writing GTK applications in python
I'd have to say that more than a few people are using PHP. In fact, of the available Apache modules, guess which one is the most popular? (Hint: it's not PyApache or even mod_perl by a long shot)
My journal has hot
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.
Like Java and Lisp -- and unlike Perl -- Python has exception handling.
Perl has exception handling with die/eval. Here is an article about it.
Lifted whole cloth from Daily Python-URL
range generates the entire sequence beforehand. xrange, OTOH, will generate them one by one.
HTH
no comment
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.
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
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/C API Reference Manual