The Python Cookbook
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.
The title "Python Cookbook" has gotta look weird to people bopping around Barnes & Noble who aren't in the know. :)
/*drunk.. fix later*/
And for those of you that can't get your hands on a python, the adder, asp, boa, cobra, diamondback, etc cookbooks are just as well packed with tasty recipes.
"Accept that some days you are the pigeon, and some days you are the statue." - David Brent, Wernham Hogg
And here I was hoping for the recipe for crunchy frog.
Kierthos
Mr. Hu is not a ninja.
Or, as Homer might add: "...mmm...python"
Athletic Scholarships to universities make as much sense as academic scholarships to sports teams.
Cornmeal Crusted Rattle Snake with Cactus-Corn Succotash
Recipe courtesy Joey Altman, Copyright 2001
2 1/2 pounds rattle snake, dead
1 cup buttermilk
1 cup cornmeal
1 cup flour
1 tablespoon salt
1 tablespoon chile powder
1 tablespoon garlic powder
1 tablespoon paprika
1 teaspoon cayenne pepper
1 teaspoon ground cumin
1 cup vegetable oil
Cactus-Corn Succotash, recipe follows
Using a sharp boning knife remove the meat from the snake by cutting down the back, just slightly to 1 side of the spine from the head to the rattle. Using the tip of the knife peel the meat from the ?rib cage?. Once you removed the 2 long strips of meat, lightly pound them with the back of the knife to tenderize them. Cut the strips of meat into 1-inch pieces and place in a bowl with the buttermilk. Mix to coat well. In a large bowl combine the cornmeal with the flour and the spices. Heat the oil in a large skillet on medium high heat. Dredge the snake pieces in the flour mixture and fry for 2 minutes or until golden brown and then transfer to a paper towel lined plate. Repeat until all the snake pieces are cooked. Serve with Cactus-Corn Succotash.
Cactus-corn succotash:
2 tablespoons olive oil
1 cactus pad, thorns scraped off, cut into small dice
2 ears corn, shucked
1 red onion, peeled, sliced in rings, grilled with olive oil and chopped in small dice
1 bunch scallions, grilled and chopped
1 chayote squash, sliced 1/4-inch thick, grilled with olive oil and chopped in small dice
1 tablespoon minced garlic
2 tablespoons minced jalape?o
1/2 cup diced red bell pepper
4 tablespoons butter
1 cup chicken stock
1 cup diced, peeled and seeded tomatoes
1/2 cup chopped cilantro
Salt and pepper
Grilling the vegetables first gives another great layer of flavor, however, it is not absolutely necessary. Just omit that step and cook the vegetable right in the pan. In a skillet on high heat saute the vegetables except the tomatoes in the olive oil for 2 minutes. Add the stock and butter and cook until mixture reduces by half. Add tomatoes and seasoning and serve with the warm snake ?nuggets? on top.
Yield: 4 servings
Prep Time: 30 minutes
Cook Time: 10 minutes
Difficulty: Medium
Python is implemented in QuArK (Quake Army Knife, a quake engine mapping tool) and is supposed to be quite useful in automating tedious procedures. Definately have to give it a look-see next time I'm at B&N
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.
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.
Best Slashdot Co
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.
I've been seeing a lot of complete shit like this lately. What ever happened to compiling it? Jesus. It might make your review seem a bit more credible if you said "despite all the new stuff that keeps appearing in python, their online documentation is excellent so be sure to download the newest version at www.python.org". Or something. Nah...you have to turn it into some kind of distro bashing.
I have to ask (given my Python illiteracy), does Python have built-ins for such an operation? Or is this just "how to implement an old trick" to "get your feet wet" with Python?
If my coffee is working correctly this morning, I'd assert that any language with an XOR-assign could accomplish this feat (with the added restriction that the vars be of the same size, or operations are performed iteratively on byte pointers).
Below is chapter 1 of my new C cookbook:
A ^= B;
B ^= A;
A ^= B;
Short chapter.
Pythons? I heard they taste like chicken!
[alk]
Some sort of snake, perhaps...
Best Slashdot Co
Don't you mean QuArK is implemented in python?
You twat.
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.
a,b = b,a
The perfect companion piece to Bake a Snake.
daed si luap
What a twisted conglomeration.
It looks more like Monty Pyhon's Cookbook. Oih, did you say SPAM?? SPAM SPAM SPAM!!!
My hovercraft is full of eels
May I please fondle your bum
Some drink at the fountain of knowledge. Others just gargle.
thats ok, i got modded down for a spam reference.
Moderators are so anxious to mod down that they forget to think first
Who run Barter Town?
Actually, this is an undefined behavior in c and c++, and you'd do well not to rely on it doing what you expect.
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
I used to code in Python, and now I use Ruby in it's place. I've found it to be just as readable but more terse. It's also extremely consistent in the way that everything is an object. You can say things like
5.times {|n| puts n}
and all kinds of other crazy things. I'm not saying it's better than Python(not trying to start a flame war). I'm just saying to try it and see if you like it.
A musician without the RIAA, is like a fish without a bicycle.
Ah, fond memories. I remember showing that to a friend a while ago. He looked at it all cross-eyed, then ran off to see if it actually worked. Five minutes and a "holy s**t!" later, I knew he got it.
And there isn't anything wrong with implementing an old trick to get your feet wet in a new language. "Hello, world!" is a classic for a reason. When you are learning somethign new, any tie you can make with what you already know is helpful.
Thomas Galvin
No, it isn't.
no it's not.
it's only undefined when used like:
a ^= b ^= a ^= b;
(or whatever it usually is, i haven't memorised it 'cos it's wrong!)
doesn't python have tuples, so you can do:
(a, b) = (b, a);
(caveat: i don't know python!)
If I may perpetuate the cliche, I looked at that cross-eyed, worked it out, and said, "Holy s..t!"
$ python Python 2.0 (#1, Nov 5 2000, 21:13:18) [GCC 2.95.2 19991024 (release)] on sunos5 Type "copyright", "credits" or "license" for more information. >>> a='hello' >>> b='goodbye' >>> (a,b)=(b,a) >>> a 'goodbye' >>> b 'hello'
O=='=++
Sorry - forgot to select "Text Formatted" for ... (and danged if I'm going to convert
this cut and paste in my post from a minute
ago
all of those ">" to ">".
$ python
Python 2.0 (#1, Nov 5 2000, 21:13:18)
[GCC 2.95.2 19991024 (release)] on sunos5
Type "copyright", "credits" or "license" for more information.
>>> a='hello'
>>> b='goodbye'
>>> (a,b)=(b,a)
>>> a
'goodbye'
>>> b
'hello'
O=='=++
Bah, that's waay easier in Python:
(a, b) = (b, a)
bn.com has this book listed for $31.96. Get it from Amazon for $27.97
Save some money!
Bigger question: Who cares if you can swap values without using a temporary var? Is this important in some way?
No really, I'm no CS major, I have no idea.
This is almost exactly what you want (assuming you have the Perl Cookbook in hand):
m l
http://pleac.sourceforge.net/pleac_python/t1.ht
No, he doesn't, although he could have worded it better.
QuArK is not implemented in Python.
Scripting is implemented in QuArK, using an embedded Python interpreter.
Smack!
It's not really a big deal, but looking for little tricks to deal with little problems is good practice and gets you used to trying to think of multiple ways to do something. Training yourself to attack a problem from multiple directions can be useful when trying to find a solution to a more difficult problem.
I've got a mind like a steel trap - it's got an animal's foot stuck in it.
I probably do as much preaching about Linux as he does about God - maybe we should get it declared a religion and get tax-free status
There is already a so-called Church of Emacs. You don't want to dance with the devil.
Will I retire or break 10K?
That is a great resource. Now one needs the inverese (perl version of python cookbook) and to roll them into one.
Some drink at the fountain of knowledge. Others just gargle.
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
Irritable, left-wing and possibly humorous bumper stickers and t-shirts
Yes, it is: look here
That doesn't say the behaviour is undefined. Just that it may not be as efficient as you think it is.
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?
No no he's not dead, he's, he's restin'! Remarkable bird, the Norwegian Blue, idn'it, ay? Beautiful plumage!
I believe swingkid may be referring to the fact that if a and b are aliased to the same location in memory, the "trick" will go wrong (zeroing the value).
But why would you swap something with itself?
It would be almost impossible to achieve the aliasing in C, the only ways I can think of are:
1) swap(a,a);
2) union {int a; int b;} u;
3) #define b a
[or anything similar, i.e. int* b; b= swap(a,*b);]
I would say that if you are swapping something with itself, you have a problem with your algorithm.
The parens aren't necessary. They are in Perl5, however.
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/
Yeah, like the guy who drew Tux, whatshisname..
Escher was the first MC and Giger invented the HR department.
In my own experience, I've experienced the opposite. I was pretty good at procedural programming, but the OO stuff always seemed rather intimidating.
Then a friend twisted my arm and made me learn Python, and it wasn't necessarily that Python does OO well, but that it makes it really quick and easy to experiment. Doing so gave me sufficient understanding to go back into Perl and figure out how packages and modules and such work.
I think it's more likely that (s)he's thinking of the a ^= b ^= a ^= b version, which is often touted as swapping a and b, but is undefined (modifies a twice between sequence points). This is an old chestnut on comp.lang.c which (s)he appears to read.
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.
Oh, blow it out your arse. Python is an object-oriented procedural language with some functional aspects thrown in for good measure. Python was never trying to be Lisp. And thank Guido for that!
the growth in cynicism and rebellion has not been without cause
a,b = b,a
Pretty sure it works the same way in MATLAB, too, but I don't have mine here to check...
Why? The OP didn't write that version, (s)he put sequence points after each operation. And, the comp.lang.c article swingkid linked to said nothing about that at all (it has the sequence points too). The only things it did say were that it only works on integral types (but that should be a compile time check) and that it goes wrong if a and b are the same location in memory. Oh, and that the "trick" is useless if your processor has registers (it probably does...)
- Andrew (going AC)
more concise: a^=b^=a^=b;
You cannot proceed from the informal to formal by formal means
Well, there's egg and bacon; egg, sausage and bacon; egg and spam; egg, bacon and spam; egg, bacon, sausage and spam; spam, bacon, sausage and spam; spam, egg, spam, spam, bacon and spam; spam, sausage, spam, spam, spam, bacon, spam, tomato and spam; spam, spam, spam, egg and spam; (Vikings start singing in background) spam, spam, spam, spam, spam, spam, baked beans, spam, spam, spam and spam.
Or lobster thermador ecrovets with a bournaise sause, served in the purple salm Mr. Bunor with chalots and overshies, garnished with truffle pate, brandy, a fried egg on top and spam.
[of course from Monty Python's SPAM Sketch]
Heh, Dumb and Dumber. I actually paid money to see that in the theatre.
people who send HTML mail are going to be the first against the wall when the revolution comes.
Congratualations on a thoroughly short-sighted viewpoint.
HTML email is not just for spammers.
The ability to send HTML forms to employees is a boon among other benefits.
Maybe you've never shared the joy of sending an HTML birthday card to your child or parent.
Perhaps sending A4 pngs around would be more to your liking?
The ability to communicate with the richness of HTML expression should be embraced and standardised not spurned.
aw, well. smash the HTML presses
There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
Shouldn't it be a cartoon left foot, disembodied just above the ankle? You know like that one in the... Oh... Never mind.
Perl looks like an explosion in an ASCII factory.
C - A language that combines the speed of assembly with the ease of use of assembly.
too bad that only works on things that XOR makes sense for. What happens when you have lists of sockets? Or want to swap objects that aren't the same size?
Tuple assignment is much more interesting, and, while showing "a,b=b,a" is trivial, showing how & where tuple assignment can be used is an important thing to pick up if you're comming from languages which don't allow such constructs.
my sig's at the bottom of the page.
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.
Some drink at the fountain of knowledge. Others just gargle.
You're kidding, right? No, seriously - you've GOT to be kidding. No individual with even the most basic knowledge of Python and Lisp could possibly make such an asinine comment. /. to intrigue and amaze slashdotters everywhere who would look in awe upon your brilliant post and say, "Hmm... it's the most insightful post I've ever read."
You took a cursory look at Lisp and Python. You noticed some similarities (weakly typed, compiled and interpreted, excellent for prototyping, procedural and object-oriented, common key words like "def", "class", and "lambda"). You checked dates, discovering that Lisp has been around for a helluva lot longer than Python. Then, like a class-A flamer, you got the idea that by putting it all together you could manufacture some deep and meaningful "ubergeek" post on
Your post is not even good enough to be flamebait - it's just laughably misinformed.
Wow, what a rebuttal. In light of these new facts, I'll be reconsidering my use of Perl in favor of Python. Thanks!
A troll? Really, all your objections are just about matters of taste, mostly about minor syntactical issues; so your critique is pretty subjective. Python is only two years old? Where'd you get that idea from. Or did you dredge up some old troll from the past? You come across as very pompous.
I'm still teaching myself the deeper mysteries of Python, but its always been my favorite language: clean, simple, easy to learn, and very powerful. So, while I understand the reviewer's confusion over the author's methodology, I'm more troubled by the fact that the writers seem to have overlooked one of the nicest features of Python:
from __future__ import *
*poof* Instant time machine. Your snazzy 1.5.2 classic scripts can now use facilities they didn't have before. It would seem easier to write a good chapter covering this element, let people know that it's available, then use 2.x.x for all of your examples. Anyone who needs to catch up (or stay behind, relative to your perspective) can do so with very little pain.
Beats the hell out of starting over from scratch.
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!
I have seen languages come and I have seen languages go. I have personally written compilers, interpreters, translators, instrumentation preprocessors, etc., for ten or so. Python is probably the weakest addition to computer science in quite some time; it is arguably a giant step backward.
I won't respond to this. I'll just offer a translation: "I'm a smart expert and I know what I'm talking about. Really. I'm a REAL expert. Listen to me."
Talk about f'in hogwash.
It is a very undisciplined programmer indeed who would rather rely upon error-prone white space placement than upon precise delimitation of ranges by actual tokens.
And it's a fuckin' moron who can't use a decent enough editor to 1. deal with spaces/tabs issue and 2) has so many levels of indentation in their code that it isn't obvious what belongs where.
to assign semantic significance to white space
With all your expertise I'd think you'd realize that the whitespace has SYNTACTIC meaning but does not affect the SEMANTICS of the program (after you parse, you don't keep the whitespace ... or any tokens for that matter ... around).
Python does not support declarations of variables
Humm, neither does LISP. Nor is it necessary. And your argument about initialization is a joke. In C if I write "int i;", it isn't initialized. And a new programmer might think it is. Which is worse? Declarations are a waste of time. If typing is needed for performance reasons, you should be able to add it later (ala LISP). But to require to get code to run. Humph.
patched a posteriori
Humm, "patched inductively"? or perhaps "patched from derivations by reason"? What the fuck, are you just making up meaning as you go? "Patched after the fact" would have worked nicely. Go back to your computer cupboard and leave the Latin to the adults.
The author of Python has the nerve to trumpet the amazing flexibility of its data structures. I hate to burst his bubble, but he doesn't offer anything that LISP didn't offer forty years ago.
Yeah, well, when it took C and C++ the better part of twenty or thirty years to gets list structures into the language (via STL), I personally consider it a step FORWARD when a language includes it (lists and other high level data structures) from the beginning.
Python is only two years old.
You don't know ANYTHING, do you? If you think Python is two years old, I'll let the statement stand and let that claim RUIN your credibility. (Hint: Python is NOT two years old.)
BTW, I'm no one and I know nothing. I'm just making random comments.
Regards,
Mark
Thanks for that opinion. I will list some of the reasons i prefer python to any other language i've used. Oh, i see you've already listed them for me, thanks!
No bracing
Clean formatting
Flexible
Built for "real world" programming
Larry Ewing
[Science] is one of the very few things that raises human life a little above farce and gives it the grace of tragedy.
In my experience, 75% of the value of a development platform in the real world is determined by how it answers the following question: How fast can I get the work done?
> But it isn't made clear how the interpreter decides what is more deeply indented than what.
The algorithm that Python uses is described here.
Parser doesn't see spaces/tabs, it receives INDENT and DEDENT tokens from lexer.
you're points against Python
Your spelling really helps your weak arguments.
Yep, I don't understand the hype about Python either. So many times I find myself annoyed by its syntax.
It's not important. It's not even a good idea.
Using a temp variable isn't any big deal, and this XOR trick won't be efficient on many computer architectures. And if a and b are somehow aliases for the same variable, this trick fails miserably.
I doubt anyone would try this in real code; I hope not. Imagine someone else comes in and tries to fix bugs, and then sees little "tricks" like this one. It's tough enough to find bugs in clean, straightforward code!
First, you rely too much on denigration of people using the language. To wit:
I think your arguments are weakened rather than strengthened with this tone.
Python is probably the weakest addition to computer science in quite some time
Oh, so languages exist to advance computer science? How about being useful?
On to your arguments...
Your first two points about white space delimitation should be numbered, since they come from straight from the immortal canon of Python detractors. I won't rehash the debate too much. I was at first put off by this feature also. However, other aspects of the language drew me back, and after acclimating myself to this feature I can now say I REALLY like it. It is a small part of a overall philosophy of developing maintainable software that grows on you (the philosophy, not the software).
Oh, and #2, and #5 are the numbered responses I have chosen for you today:
#2: The requirement to delimit with whitespace avoids scoping errors common in some languages when no delimiters are used for single line blocks.
#5: The requirement to delimit with whitespace enforces a matching between scoping and its visual indicators, making maintenance easier.
It's interesting that you would raise some minor nits about syntax with Python, and then bring up Perl!!! Perl is jokingly referred to as a "write-only" language because of the way it tersely uses complex syntax, side effects and multiplicity of allowed constructs. I don't intend to detract from Perl - it's combination of terseness and expressive power are very useful for a wide range of applications, and appealing to a large number of programmers.
Having translated large programs from Perl to Python, I can say that in my experience the expressive power of the languages is similar. The difference is that 6 months later I can read my Python code.
Also, having written and maintained large programs with Python, I can tell you from first hand experience that the other "problems" you mention (lack of variable declarations, tuple singleton syntax) simply aren't a big issue, if an issue at all. I'm trying to remember if I've ever even declared a singleton tuple...
As for your attack on Guido (the author of Python) you'll have to be more specific. When did he say Python had more flexibility than Lisp? This is a strawman you set up yourself. Python has very flexible data structures, probably borrowing a lot from Lisp and other languages. It's the entire package of simplicity in design (everything's a namespace), enforcement of rules to enhance maintenance, and expressive power that characterize Python.
I know you'll think this is condescending, but why don't you give the language a serious try before condeming (or indicting) it. Your arguments come off as puritanical nitpicking by someone unfamiliar with the "karma" of the language. I have used it for several years, in both personal and commercial settings, for both large and small programs. And it has worked very well for me.
Isn't that the ultimate test of the value of a language?
They rock. You have GOT to try them.
> Amusing, indeed--but this was excusable when it was penned 23 years ago. Python is only two years old.
Huh? I've been programming in python for 6 years, and I think it was around for at least a few years before that.
Your comments about using indentation to represent block structure clearly indicate that you have never actually used the language. I shared those opinions before I started working on a project that used Python. In practice, using whitespace to reflect the block structure is simply not a problem.
build for lazy programmers...
Larry Larry Larry... You almost fooled me, but you really should try to hide your identity more careful.
The issue of tabs and spaces being mixed is well known and debated in the Python community, and mixing is considered very poor form. There are code checkers to avoid this, and Python can be run to reject mixing as a syntax error (personally, I hope this becomes the default in a later release).
I'm not entirely clear what you mean by this, "handle" is not clear term. Perhaps you mean, based on the variable name, you cannot tell the class? (Neither by name, nor by looking back in the code for a declaration on that name)This is true. Perhaps you do not understand the style of programming that Python encourages -- it's roots lie in Lisp and Smalltalk, not C or Fortran. I.e., fully dynamic typing, where an object's type is incidental, but it's properties are essential. If you don't understand that kind of programming, lack of typing will seem like a deficiency.
Not true. Variables spring into being when you initialize them. Python is not like PHP or Perl in this regard -- there is no default value for an uninitialized variable.Lack of declarations is not a large source of bugs in actual use, and those bugs that do exist are shallow and easy to fix. Deep bugs are dangerous, but this does not often lead to deep bugs (though language that allow uninitialized variables can get themselves into trouble).
It's built-in data structures are useful, and C (and even Java) are simply lame not to include them directly in the language. Lisp is another matter (though, again, the literal data types available are slim). Python tends to have fairly Lisp-like semantics, and that's okay. Designers of Python have never claimed to be revolutionary -- rather, they have tried to take the best features of languages that have come before, and create a language that puts them together in a pleasing way (unlike, say, Perl that takes every feature, throws them into a big heap, and calls it freedom). Such as? [ ] and { } are taken (and by data structures that are used more often than tuples). It works, and you get over the (x,) thing really quickly.Obviously from this critique, you have never seriously used the language. You only are able to critique its outermost veneer of syntax, and you don't have the knowledge to make any comment on the power of its semantics. The wise language designer knows semantics are more important than syntax (though syntax can get in the way, Lisp being the primary example).
pyhton isn't special because it can do crap like that. you can do that in basic. or c. or ada. or assembly. whatever.
b = a + b;
a = b - a;
b = b - a;
there's a few ways to solve this problem, and using white-space agnostic languages to boot.
my review from amazon:
This book is more like an encyclopedia than a cookbook - each section is introduced and written in a different style and different sections are stronger and more cohesive than others. Some sections are bursting at the hinges and others feel like they are incomplete (like the algorithms section).
The introductions to each chapter alone are worth the price of the book. Each introduction is written by a different Pythonic luminari, such as Fredrik Lundh, Tim Peters, Alex Martelli, Guido van Rossum and many others. These literary pieces are insightful, humorous and excellent.
I love python, it follows Albert Einstein's principle Everything should be as simple as it is, but not simpler . As such, this book plays a valuable addition to my library. However, if you are just starting out I would recommend getting a different book first.
By the way - Redhat ships with python 2.2 you
just need to change your #!/usr/bin/python to
#!/usr/bin/python2
Anthony
Don't make a scripting topic and expect all talk of python and perl to be done there. they are both full programming languages. (as are others such as tcl)
scripting is something can can easily do with them but should not be portrayed as a limitation.
congratulations, you have just created not one, but two temporary variables -- which are, in fact, first class objects, requiring instantiation. Efficient.
Companies basing their business on Python should take a look at the PBF http://www.python-in-business.org
UberGeek! Cool - never heard that one.
I'd wager that since that averages out to 12 seconds per query that your metric is useless, besides DB queries reflect the database more than anything else, all the language does is send a string off to a C API which then queries the DB and gets the info. Same thing with the GUI. A better metric for the language would be say processing large amounts of data.
Photos.
You forgot the part where A and B are declared as 'float', and so this clever trick is really stupid and/or invalid, a lot of the time.
"It's overkill, of course. But you can never have too much overkill." - Anonymous Slashdot Coward
Yep yep, your attacking his spelling sure shows how weak his argument is. Plus, it's easier then actually finding fault with the content of what he said.
Ah yes, another attack from yet another person too cowardly to actually own up to their writing. I don't normally make mistakes like that, but I am big enough to own up to them and correct myself when needed. I can't say the same thing about most ACs.
For the record (without even using a dictionary):
their = possessive
they're = they are
there = not here
It's a typo that's all. I made a mistake.
Please mod this post only if you think others should/n't read this. I have enough ego^H^H^Hkarma. Thanks!
b = a + b;
a = b - a;
b = b - a;
In the case where you're using unsigned integers with wrap around semantics, yes. In the case that a,b are floats, integers on some systems (this won't work on signed magnitude systems, or in programming languages (like Ada) that have overflow checking), it doesn't work. It's nowhere as clear as "a,b = b,a", and doesn't work on general variables.
Trust me, it's not nearly as funny if a snake really did want to eat you when you were younger.
(Yes, one actually did, during a visit from a zookeeper to my school to show us what reptiles were really like. I was sitting at the end of a line of small children, and it started coiling around me... :-o I can handle spiders, or enclosed spaces, or high altitudes, but to this day, snakes scare the living **** out of me -- unless I'm programming in one, of course.)
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
T'Pol: It's a Klingon delicacy... But only when it's alive.
Hoshi: [Winces]
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
And even more wrong, in just about every language I know that supports an xor-assignment operator, because it modifies the same variable multiple times in one statement. :-(
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
FreeBSD? ports? 2.2? 1.5? take your pick.
-P
You make it sound as if "scripting language" is some kind of negative term. Hey, scripting languages have their strengths and weaknesses. You couldn't run the WWW without them, but I'd never use them to write CPU-intensive programs. And it's interesting to compare them to each other.
Anyway, you seem to be saying that next time we get a story about Ruby or TCL, we should lump them together with all the "other" programming languages, despite their kinship to other scripting languages, such as Perl, Python, and PHP.
...But I couldn't eat a whole one.
SCNR. :-)
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Problem is that it is the OLD (ahem) 1.5 something python. I want to use quark but it has the old python and I have the new python already installed... not sure how well those two will play... if they will play at all.
The same problem occurs in relation to bash as /bin/sh. Try making something like ash or ksh the system's /bin/sh (cd /bin; ln -f ksh sh) and watch Red Hat's system scripts break. This is bad because /bin/sh should either be the original Bourne shell or Korn shell (which reportedly comes closest to POSIX shell specifications), but Red Hat relies on many Bash extensions.
To be or not to be; that is the question, Whether 'tis nobler to suffer the slings and arrows of outrageous fortune, or by opposing, end them. . . .
You mean, apart from the most popular functional programming language, Haskell 98? Which, by the way, is strongly typed but doesn't have variable declarations. And doesn't have any flow control either (obviously). You need to get yourself a new paradigm.
"Well, put a stake in my heart and drag me into sunlight."
To be, or not to be, that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune;
There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
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.)
so you'd prefer me to send you a png attachement,
or maybe an html document in a gzip?
It seems like you are troubled by the poor use of HTML email not HTML email par se.
And what happens when you need to make a change to that form? Why not just stick it your own private webspace?
It's a little thing called 'convenience'. It aids workflow. I know it's only a little step but imagine getting a letter saying "there's a picture on the noticeboard, go look at it". HTML improves the flow of communication. People are not always great at mentally task switching and when they are "reading their email" firing up a browser breaks that task.
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".
I'll take that as a "no". Last time I looked I couldn't embed sound and video in a store bought card.
Again, it's the immediacy that's makes the difference. Imagine opening your card and getting a note "your card is on the table" and looking to the table there is your card on public display.
Email is a provate thing, the web is a public thing. Even if it's on the LAN the psychology of it makes a difference.
I fail to see how this could be made richer by adding HTML.
For in that sleep of death, what dreams may come
HTML seems to be used as a means to doodle on the email, rather then add any information or emotional empact.
So what? Should we be disallowed enjoyment because *you* can't see any benefit?
Why do webs sites use colour, graphics, mark up, tables etc. etc. ?
because people like them
Now I do concur that having HTML mail on by default is a crazy idea. 99% of the HTML mail I receive is either better as plain text or better to not get at all.
but to suggest I should be "the first against the wall" because I want to send an HTML christmas card to my friends is short sighted, rude, offensive and promotes banality.
There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
so you'd prefer me to send you a png attachement,
Yes, if what you want to send is a bitmap graphic.
or maybe an html document in a gzip?
Yes, if what you want to send me is an html document.
It seems like you are troubled by the poor use of HTML email not HTML email par se.
Yes, but as you say
99% of the HTML mail I receive is either better as plain text or better to not get at all.
If it weren't for that 99%, there wouldn't be enough reason to support HTML email in most email clients, especially as it has had so many security holes and privacy leaks.
there is your card on public display.
Why would it be? All the webcard services give you cookies in the link to make sure it's not on public display.
Should we be disallowed enjoyment because *you* can't see any benefit?
Should we all fall silent when you enter the room, because we may offend you? It brings me absolutely no benefit, and I feel free to bitch about it. Feel free to ignore it, but I don't see why I should shut up, because you like it.
Here's the best substitute for a ternary I have seen so far:
>>> (falseResult, trueResult)[bool(condition)]
(Reality reasserts itself sooner or later.)