Learning Python, 2nd Edition
Python is a dynamic, interpreted, object oriented language used for both scripting and systems programming. Python is known for being easy to learn and use, while also being powerful enough to be used for such projects as Zope and the Chandler project. Its growing popularity is also based on its reputation for fostering programmer productivity and program maintainability. One drawback sometime cited is its relatively slow execution speed compared to compiled languages such as C.
For myself, I have probably read too many books about Python, but that is because I am an amateur hacker who learns programming slowly, and I find that reading several books about the same topic, covering the subject matter from different angles, allows me to better absorb the material. For me, this was a good review of the core language and a welcome refresher course on the newer aspects introduced in versions 2.2 and 2.3. For anyone who is new to Python and wants to learn from the ground up, this book would be a great place to start.
Mark Lutz is an authority on Python and one if its leading teachers, with both Learning and O'Reilly's Programming Python to his credit, as well as the courses and seminars he teaches professionally. In updating the original version, which was already very good, Mark has polished the chapters on the core language to a nearly perfect level, while his co-author David Ascher has done the same on the more advanced aspects of the book. In addition, Mr Lutz has benefited from extensive feedback from students and readers, and his explanations therefore anticipate common misunderstandings. Each chapter is accompanied by a problem and exercise section and answers are included at the back of the book.
A major addition to the new edition is a chapter on "Advanced Function Topics," including list comprehensions, generators and iterators. Python is sometimes used with a functional programing style almost similar to Lisp, although to List purists that may sound like heresy. The recent versions of the language have significantly upgraded Python's support for the functional style. Functions cover three chapters in the 2nd edition instead of just one.
Another major change since the first edition is extended coverage of Modules, which now occupies four chapter instead of just one. Python modules are a high level package structure for code and data, and they help facilitate code reuse. Yet another addition is coverage of Python's "new style classes." Coverage of classes and object oriented programming has been greatly expanded and now includes five whole chapters and almost 100 pages. Coverage of exceptions now is expanded to three chapters.
If you have been considering learning Python, now would be a great time since this new book is the perfect introductory text. If you already know Python and have read the first edition of Learning Python or another introductory text, then this book may not be essential since the new language features are covered pretty well on the web in various places, and you might be better advised to read one of the other fine books on non-introductory aspects of Python. But this book is about as good an introduction to the language as you are likely to find. The book does not cover all of the Python libraries nor many other topics, but it does briefly touch on the major libraries, frameworks, gui toolkits, and community resources.
If you want to learn the core Python language quickly, this may be your best bet. Learning Python only covers the basics, but it is deep in information on what it does cover. Well written, understandable, and in a very logical arrangement, this book is densely packed with info.
I have often found myself returning to the original book, and the new book will now fill this role. It is deep in information, well written, and a joy to read. For an experienced programmer who is just learning Python, it may be possible to thoroughly learn everything about the core language in one reading of this book. For relative newbies, it will be an often-used resource.
To read more reviews of books about Python, visit the Python Learning Foundation. You can purchase the Learning Python, 2nd Ed. from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.
...can be found here.
I prefer Ruby, but there seem to be a lot of healthy discussions of various language features and ideas across the scripting language community. The "Python comparison page", for example, has a link to John Ousterhout's paper on why scripting languages are useful - even thought he wrote the paper about Tcl, it's just as applicable to Python or Ruby.
The Army reading list
"Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we're looking for more people with skills in this language." said Peter Norvig, director of search quality at Google, Inc.
Open source, expressive (very short code can achieve a lot), readable (very short expressive code is easily groked -- fewer bugs), no direct pointer manipulation (safe -- fewer bugs), integrates nicely with other languages, runs on a variety of platforms, very easy to learn.
I, too would recommend learning python. It is a very good, language. Zeolotry is another thing though. Keep your mind open. Learn all the languages you can. This book, I can't comment, although I received it a week ago I haven't gotten around to reading it yet.
I have the fist edition of this book. It has help me considerably, but it seemed as though I always had to use google to supplement it with code/examples. I guess I wanted to see more real world work in the book rather than what seemed to me to be generic theory explained via simplistic samples.
Maybe its just me though.
The / in
I have nothing against python, but every time you ask a python nut why they choose to code in this language, the response is always something to the effect of "it's easier than perl". I don't mean to troll here, but does python have any merit of its own, or do people only use it because they don't want to use perl?
"Quoting famous computer scientists out of context is the root of all evil (or at least most of it) in programming." - K
While TCL remains my personal favorite, Python is really good, except for the creating-your-own-extensions part. The Python's C API needs a lot of catching up to do to match the excellence of TCL's.
In Soviet Washington the swamp drains you.
This is not a religious argument; I'm not advocating that python is the one language you should use or anything like that. In fact, not having an "ideology" is one of python's major strengths.
If you're asking "why python", ESR has said it better than I ever could.
I'm yet another of those who experienced extremely small turnaround times for python programs. It took me a week, working part time (I estimate about 30 hours) totally, to release 1.0 of gretools, starting from scratch. I had not written a single line of python code before that, mind you.
Why python is great:
Its not a religion. It doesn't force its style of thinking on you. Functional programming, excellent string manipulation tools, classes, inheritance, exceptions, polymorphism, operating system integration, they're all available. This is python's biggest advantage. Whichever background you're coming from, you can very quickly become effective at python.
Incredibly compact code. This is largely a consequence of the previous point. Apart from that it is dynamically typed, and has lots of other cool features. Like doing away with braces for delimiting blocks. People who know nothing about the language flame it for using indentation, but I have never found it confusing, and it makes the code smaller far more readable.
A user-friendly programming language! You aren't going to believe this until you've actually programmed in python. Its got this amazing property that if you can express a thought in constant space mentally, then you can code it in a constant number of lines, most of the time in a single line. In other words, the abstractions of the programming language match the "natural" abstractions of programmers very closely. After just a couple of days I got so used to this that I began to "predict" language features intuitively. At one point I just knew there had to be a language construct for something I was trying to do, and found that it was the reduce function.
Simple syntax. Python manages to have all these features while retaining a very simple syntax, perhaps even simpler than C. This is a big plus, because it gets out of the way and Does What You Mean.
Convinced? Get started now!
awk, sed, grep, and nc.
You need to be able to bind to a socket.
(Of course, if you're really clever, you add 'gcc' to the list, and then you can use awk, sed, and grep to compile short C programs to do the socket interface for you)
Except that Python uses dynamic typing, not static typing. Variables are untyped but hold references to typed objects.
> There is nothing, and I do mean NOTHING that
> a real Unix professional can do with Python
> or Perl that he or she can't do with awk, sed,
> and grep.
Awk? Sed? Bah! There's nothing you can do in awk and sed that you can't do with plain, simple assembly language opcodes!
The Army reading list
If there's anything I hate, it's these big, thick, 1000-page (or 500-odd page) books which tell me how to use the Help system in Appendix 42.
So, I'm always wary.
Python doesn't have static typing; it has dynamic typing like Lisp, Ruby, Perl, etc. The difference between Python and Perl is that Perl has rather weak dynamic typing. For example, Perl tries to treat strings and numbers as the same type (resulting in the use of strange constructs such as the value "0 but true"). Python and most other dynamically typed languages have stronger typing, with distinctions between strings, integers, floats, etc.
Static typing means that each variable is only allowed to hold values of one type. Usually the variable types are manually declared (as in C or Java), but some languages (like Haskell, IIRC) can infer the types.
I don't think *all* the O'Reilly books are good but the Python books (I own several) are really excellent: they are written by people that have been involved with the language for a long time and that really *think* in Python and like the language. Glad to see Python is still doing well.
there's no place like ~
Agreed, asm is the way to go!! Not only that, it's cross-platform, and high level!! (HLASM!!) Oh yeah, and did I mention how easy it is to learn asm? I have such an issue coding REXX, so I switched to HLASM now it only takes me 20 minutes to could a copy program!! Yeah!! Progress baby!
This sums it up really:s id=3882
http://www.linuxjournal.com/article.php?
I like Python because of the line numbers and the goto statement. Why don't they add those features to Visual Basic?
If tits were wings it'd be flying around.
odbc module so python will not be in my toolbox.
And don't tell me to do it. I haven't used c in a decade.
I would recommend "Python In A Nutshell" as it cuts to the chase and doesn't teach you programming so much as giving you what you need to know in Python. If you can already program, the "Nutshell" book is pretty good, plus the author can always be found around the Python Newsgroup(s).
And you only need 4 opcodes! (add, branch, load, store)
One more time, for the majority of people who don't understand:
Strong typing is when your language will only allow appropriate operations to be performed on values of the appropriate type.
Weak typing is the opposite, where a language will implicitly convert between (possibly incompatible) types or will simply allow any operation to occur.
Static typing is when a language enforces its typesystem (whether it be strong or weak) at compile time.
Dynamic typing is the opposite, when a language enforces its typesystem at runtime.
Python is strongly, dynamically typed. If you try to perform an integer operation on a string, it will check this at runtime and raise an exception. It will not perform the operation.
Perl is weakly, dynamically typed. If you try to perform an integer operation on a string, it will implicitly convert that string to an integer (using 0 in the case of strings that aren't a valid representation of an integer). It does this at runtime.
Haskell is strongly, statically typed. If the compiler cannot prove that all your operations are performed on values of the appropriate type, it will not compile your program.
C is weakly, statically typed. It will implicitly convert beteween incompatible values (pointers and ints, for instance) but it will determine which implicit conversions will occur at compile time (as well as reject some other conversions or type errors).
Python is not in any way statically typed. Perhaps only moderators who actually know Python should get mod points on articles such as these (yes, I know that'd be impossible, but it'd ridiculous that the parent post got modded up to 5, interesting when it's blatantly and obviously wrong).
Jeremy
Looking for a Python IRC bot?
WTF? Didn't you RTFA? Python is not just a scripting language, it's a systems programming language.
LOL.
I hear both the PS3 and the X-Box 2 will use Python as their fundamental OS platform, and also for writing vertex and pixel shaders.
I'm not sure which Python you're referring to, but it doesn't sound like the www.python.org one!
Python's intellectual ancestor was the language ABC, not Perl or TCL. Python's object system is very clean and well thought out, not accreted into the language. New style classes are an elaboration of that, merging the concept of a type and a class.
I'm not sure which "aspects from Camel" fuck up the whole situation. You're one example about continuations and GC "occultism" doesn't really help. 99% of the wonderful Python applications out there have no need of such stuff, and if you did, maybe Stackless Python (a variant) might interest you.
Python has all the necessary features to build very robust and maintainable systems. It's library is excellent, and it's C API is extremely clean for both embedding and extending.
A valid criticism for *some* applications is that it's slower than C or C++. This should come as no surprise since Python is interpreted and highly dynamic. Fortunately, Python can easily be extended such that critical sections can be coded in C, although most applications won't need to bother. It's also an excellent prototyping language so that if you *did* want to rewrite it in a static language like C++, you'd have an excellent basis for it.
Can I see sample code for awk, sed and grep that creates a curses interface or supports polling multiple processes (ie, the select() system call or equivalent)? The curses interface can be lived without, of course, but a tool that can run multiple processes (ie, ssh to multiple machines, connect to port 80) and collect output is quite useful. Curses helps display the output.
Well, from the perspective of a long-time Perl developer, Python has a certain elegance in it's language design (apart from using whitespace as syntax ;) that some other languages lack (in fact, it reminds me of Smalltalk in many ways, for this very reason). It has taken many of the features from various object oriented, functional languages, and scripting languages, and tied it up in a nice, clean, consistent little package.
OTOH, Perl as a language is unbelievably flexible and convenient to work with, but it's most definitely a more "hackish" language, in that it's grown more than it's been designed. As such, it's definitely more of a developer's language (ie, has many of the features which, while not necessarily incredibly elegant, are *really* convenient) than a theorist's language.
So, then, why pick one over the other? Frankly, in the end, I suspect it's just personal preference (or predjudice).
Isn't that reason _enough_? Some people may not know what they want, but just about everyone knows when they DON'T like something. Perl makes me itch.
The result can be seen when you try to program a caller frame instance-preserving continuation in Python
You're right. This sort of thing is attempted all the time by inexperienced C programmers who just don't know better than to try to program a caller frame instance-preserving continuation in Python.
All these programmers who think Python will provide all necessary features clearly need to switch to C in order to get the high-level support they need for their applications.
Python is basically an attempt to merge Perl, TCL/TK and object orientated programming.
No way in hell. Python tries its best to avoid perlisms, and TCL/Tk doesn't even come close. Python has a strongly typed object system with one namespace.
I don't think that we really have to discuss the problems of Perl's "object system"
Perls object system is a hack. Python object system fits like a glove. ISTR that Larry kinda "copied" the objsystem from Python (and not vice versa), but it didn't really fit perl.
or the shortcomings of TCL/TK.
Shortcomings of TCL/Tk have really nothing to do with the topic. Don't try to sneak TCL/Tk into this. This has got to be the clumsiest strawman argument I've seen in a while. Chewbacca lives on Endor?
The result can be seen when you try to program a caller frame instance-preserving continuation in Python.
What do you mean? Closures (or "nested scopes" as they are referred to in the language docs - look them up before whining) work as expected. Can you give an example of the thing you are talking about in a language you know (assuming you know one). Are talking about what Stackless Python is trying to do?
But when the project advances they suddenly notice that python doesn't provide all necessary features and a whole rewrite is in order.
You don't really need "features", you can use libraries to add "features" and the core language is flexible enough for pretty much any tasks.
Save your wrists today - switch to Dvorak
Actually, if anyone is interested in learning Python and doesn't mind reading a book on their computer, there's a bunch of free ebooks available on the Python Documentation page (as well as a comprehensive list of books that are only printed). I've read a few of them, most of them are pretty good, in particular "How to think like a Computer Scientist" is a very good text for a less experienced programmer and Bruce Eckel's "Thinking in Python" is a nicely comprehensive coverage of Python (not unlike his "Thinking in Java" and "Thinking in C++" books).
Even if you do mind reading books on your computer screen, most of these books (actually I think all of them) are also available as physical printed books as well.
Thinking In Python by Bruce Eckel
An Introduction to Python by Guido van Rossum, and Fred L. Drake, Jr. (Editor)
How To Think Like a Computer Scientist: Learning with Python by Allen Downey, Jeff Elkner and Chris Meyers
Dive Into Python: Python for Experienced Programmers by Mark Pilgrim
Text Processing In Python by David Mertz
Python Language Reference Manual by Guido van Rossum
Yeah, it's really sad how many large projects fail because they're implemented in a language that doesn't properly support continuations....
Wait a minute, I've been in the computer industry for decades, and other than myself, I could probably count on one hand the number of people I've met who even know what a continuation is. Other than as an amusing tool to utterly confuse any but the most advanced developers, continuations are probably only useful for coroutines, and coroutines are mostly useful for iterator generators, which recent versions of Python have generators nicely packaged in an easy-to-understand syntax (the yield statement).
Since few if any other popular languages give you even this much, it must be truly amazing that any software works at all.
There is nothing, and I do mean NOTHING that a real Unix professional can do with Python or Perl that he or she can't do with awk, sed, and grep.
:)
Proof of concept:
Somebody write Slashdot in one of the above
(Slashdot is written in Perl)
Assembly Language? Overkill!
Real programmers directly input hexcodes using cat or copy con..
One drawback sometime cited is its relatively slow execution speed compared to compiled languages such as C. this is the tradeoff between interpretation languages (python) and compiled languages (c, java). you get flexiablity in your code but you lose some speed in runtime. Well, most people use python to write scripts that are smaller than what they would write in C++ or java. you are not going to write half life 2 in python, right?...
I prefer Ruby as well, but I can already see that it's not going to be a language I can spend lots of time learning right now. Although I like programming languages, I don't have enough free time to spend time learning a language that won't be immediately useful. For the record, when I need a scripting language, I use Perl unless the design needs to be object oriented, at which point I drop back into Ruby.
I seem to have a different view of what a scripting language should be than most of the people who write them. I write scripts when a sudden need for a small program comes along. I need the script to not take a long time to write, even though I might not be ``current'' with the language. To me, the most useful scripting language would be one with strict syntax and a large mass of well documented libraries to dip into. No scripting language I've seen so far has strict syntax. ``There's more than one way to do it'' seems like it'd hurt you if you weren't well versed in the language and were trying to write a script that only needs to run once. It also seems like dynamic typing would hurt the effort as well. Eliminating as many points of unsureness as possible would be a boon. Java's syntax would make a terrific scripting language.
Anyway, that's just my opinion. I don't mention large-ish software projects because I don't have lots of experience in them.
Is this still the only modern language without a do-while loop? Do you still have to do the "while 1: ... if (!condition): break" thing?
This guy's sig. is the giveaway.
I've grown a large appreciation for Python. If it would just incorporate a few syntactic conveniences from Perl I would use nothing else. I was very resistant at first but now after writing a script in python, I somehow feel clean, like I've taken a shower.
As for this book... I have the first edition and they're programming python book. I consider them both lousy and don't deserve the same names as the perl equivalent books in the same series. Other better books are available fortunately.
One of the things I initially judge a language by is how elegant it is to code the quicksort algorithm (yes, I'm aware Python has a built-in sort function -- that is not the point). Here's quicksort in Python:
def quicksort(list):
if len(list) > 1:
pivot = list[0]
left = [x for x in list if x < pivot]
right = [x for x in list if x > pivot]
pivot = [x for x in list if x == pivot]
return quicksort(left) + pivot + quicksort(right)
return list
I'd say this speaks for itself. Enjoy.
A mention of the Psyco Python runtime compiler is in order. It's simple to use as well - all you do is put this at the top of your entry script:All routines called are then compiled from bytecode on-the-fly into native x86 code. It's not quite as fast as C - but with Psyco you can easily get close, especially if you design your algorithms properly.
While I'm here, these are the Python packages that I find essential once I have the base installation (which includes the IDLE IDE). I've used these packages under Windows, but most work on Linux as well:
Speaking of blatantly and obviously wrong...
C is weakly, statically typed. It will implicitly convert beteween incompatible values (pointers and ints, for instance)
Not without an explicit typecast, it won't.
Alternately, Perl cares more about container types than value types.
how to invest, a novice's guide
You need a book to learn Python?!??!!? My god, I'm an old C++ programmer, Python is like a gift from a god!
You just have to bang your head against the keyboard a couple of times and I bet you it compiles!
Aide-toi, le Ciel t'aidera - Jeanne D'Arc.
The spirit of what he's saying is absolutely correct, simply substitute 'static' with 'strong' and the point still holds.
Jeez, it's good to issue a correction, but the error was in name only, the concept he was trying to express is still perfectly valid.
Turn s60 photos into awesome videos with mScrapbook for all S60 3rd edition phones!
Boost.Python
I sort of hope that Parrot will help Perl overcome its introversion, and let it integrate more readily with other languages.
I think that C++ and Python form a dynamic duo. You can put the effort into compiling items that benefit from such, and glue them together in Python most agreeably.
The C++ standard library focused on Platonic abstractions, but Boost is pulling C++ in more mainstream directions. And that's a beautiful thing.
While issuing random plugs, check out Leo. It's not too often you see a fresh interface on an editor.
Get thee glass eyes, and, like a scurvy politician, seem to see things thou dost not.--King Lear
"... at 591 pages, this is a major upgrade to the 366 page original. Furthermore, the Python language has undergone extensive improvements and additions in the last five years..."
Sadly, I think Python has grown to large recently. It has lost part of its cohesion because of this. The language has been getting fatter as fast as this book between editions (+60 % pages, I mean c'mon). It doesn't fit it my head like it used to.
Does that answer your question, or is it more of the same stuff that was confusing you?
Dewey, what part of this looks like authorities should be involved?
Ugh? Bruce Eckel says in his book (Thinking in Python) that Python is weakly typed:
Now I'm really confused!
Craig
Is a book review that wasn't for lavae.
It's like going to the local bookstore and hoping for something more to buy than Learn VB in 24 Hours.
There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
That's what conversion constructors are for.
> but does python have any merit of its own, or do people only use it because they don't want to use perl?
... again a perl wart most other languages don't already share.
This turned me off of python for a while, and through the 1.x series of python, the answer was pretty much that python indeed did not have much over perl. I'm astonished perl still doesn't have formal parameters, but that's more a glaring lack in perl than a novel feature in python. Lack of funky "decorations" on variables
Now python has generators, list comprehensions (coming soon, generator comprehensions), the stackless variant (alas never to be merged into python core I suspect), cycle detection in the GC (perl will still let them dangle), extensible builtin types (you can even subclass int if you want to)... There's a raft of PEP's on track for the next revision of Python, which comes out on a pretty regular schedule, so the language development tends to iterate faster than any other I've seen.
It still doesn't hold a candle to lisp or even scheme for sheer flexibility and potential expressiveness (with scheme I stress "potential", it takes lots of work to get comfortable with scheme), but for dynamic languages, it's currently my favorite. I still do use perl for things in CPAN that are nowhere else, e.g. Net::DNS has no credible equivalent in python.
Ruby looks interesting in some ways, but I don't like its total lack of a naming convention or namespace protection for "builtin" methods, nor the extra-funky syntax concerning blocks and yields. It also doesn't seem to work very well on windows, the parser seems to outright choke on line ending conventions with code pasted from a browser. It's also really poorly documented -- I realize english isn't the native language for the Ruby community, but even API documentation is sorely lacking in organization.
I've finally had it: until slashdot gets article moderation, I am not coming back.
Heh. Sure, I _could_ write something with awk and sed to modify XML files a developer sends me. The question is, would anyone but me be able to understand the script well enough to modify it? Heck, could I, if I didn't have to do anything with it for a year?
Naked.
I'm a long time perl programmer. Recently I did some research into Python. It really does look to be a more elegant language and enforce some structure that is needed in Perl.
That said I can't justify the switch. There are just too many good modules available in Perl (esp for the engineering work I do). When python has the bredth of packages that Perl does, and when they have a nicely organized way to access said modules, I'll be happy to switch.
One should not theorize before one has data. -Sherlock Holmes-
Total agreement.
I've used python for several years, but only 2 weeks after stumbling across "Programming Ruby" (Available free at http://www.rubycentral.com/book/), I've switched all new development to Ruby. As a language, it just clicks for me. It's like the best of all possible worlds. It brings in the cleanliness of Python (without the whitespace issues, for those who dislike that), the hack value of Perl (tightly integated regex, etc), the OO of smalltalk/java (for those that like that kind of thing), and essentially anonymous functions like a functional language. Many things are expressed in a very logical manner, and this allows you to concentrate on how to accomplice a task.
A comparison:
Python
adict = {'key':'val','key2':'val2','key3':3.14}
for k in adict.keys():
----print 'k -> '+str(adict[k])
Ruby
adict = {'key'=>'val','key2'=>'val2','key3'=>3.14}
adict.each{|k,v| puts k,' -> ',v}
TODO: Something witty here...
Right on man!! Here's my code for getting system time in os/390:
:D
00000E 4110 0002 00002
000012 0A0B
000014 5000 30EE 000F4
000018 D100 30F1 315A 000F7 00160
00001E D205 30F2 30F8 000F8 000FE
000024 DE05 30F2 30EE 000F8 000F4
00002A 41F0 30F2 000F8
00002E F805 000F 30F2 0000F 000F8
It works!! And look at the address range, only 32 bytes of code for the whole operation!!
That's because the two people discussion the issue (poster and your author) have defined what it means to be weakly-typed differently. Without using a strict definition, this is what happens. Rigor folks, please, it's the only way to come to conclusions. No more off the cuff comments on CS topics. Prove it or shut up.
Anyway. I immediately ran off to the nearest bookstore and grabbed the first edition of the book. I read it once through and it--along with a lot of googling--helped me understand what I was doing, but once I had gone through it once I couldn't use it to recall the details of what I had been taught. If I wanted to look up something that I knew I had learned *from the book* I would have to look it up *on the web* (e.g. syntax or the required parameters of a function) because the index was useless. I never found anything I needed from that book once I did the initial once-through reading.
Though let's not gloss over the fact that I obviously learned python fairly well from this book because I did get the job! So sure, if you need to learn the language, the first edition did the job, but you'd better buy a *real* python book while you're there at the bookstore because as soon as you were done with Learning... it was nothing more than a paperweight.
Perl is great for UNIX scripting, but once you pass a certain point, it begins getting unwieldy (IMHO).
Python is a very powerful language, but the whole concept of scope being dependent on indentation drives me nuts. I ran away screaming in frustration after a while.
That being said, it beats the hell out of APL.
> Real programmers directly input hexcodes using cat or copy con..
Amateur. Real programmers use nothing but S, K, and apply.
I've finally had it: until slashdot gets article moderation, I am not coming back.
It gives a thorough description of how to use Python; which is indeed easy to learn if you already know another language. But when the authors say that not having to compile Python programs means that development time is speeded up, perhaps they are overstating. For most programmers who use compiled languages like C or C++, the biggest time is taken up in finding a method that solves a problem, coding it and subsequent debugging. These days, compilers on recent hardware are fast enough that link/compile times are simply not a bottleneck to development productivity. So it is a bit of a straw dummy that the authors put forth.
However, they are absolutely spot on when comparing this to Perl or Tcl. Perl is powerful, but its code looks like assembler. Perl gurus tend to shrug when you point this out, usually saying they understand it, with the not-so-implicit suggestion that if you can't, it is your fault. But this leads to a real maintenance problem and a barrier to entry to others. The cleaner Python syntax can show coding intent far clearer. Plus, and more importantly, the object oriented nature of Python lets you scale up to much larger programs. This has always been a problem with scripting languages, all the way back to the various unix shell scripts and DOS bat files. Often, the most those ever gave you in terms of modular capabilities was the equivalent of subroutines. Which is strictly procedural and not OO.
By the way, there is a small contradiction between the above claim that Python is more understandable than Perl and the claim that it has an advantage over C++ or Java because it is not as verbose as those. Typically, in increasing amount of source code, you have Perl -> Python -> (C++,Java). If you think that Python is more understandable than Perl, then by that same logic, we could conclude that C++ or Java is more understandable than Python.
So if you are using Perl or Tcl and want something better, Python is a good choice. A good upgrade path.
But if you are currently using C or C++, with maybe X for graphics, or Java, then I suggest you stay with those. All three languages, with their graphics, give you a far richer toolset. Python would be a retrograde choice.
good god ...
.... not "you're" ...
... not "loose" (not in this article, just reminding. You're getting too loose with your English and you may lose your grasp.)
"your"
it never ends!
it's "lose"
Actually, the python version would be:
adict = {'key': 'val', 'key2': 'val2', 'key3': 3.14}
for key in adict:
print 'k -> ', adict[key]
Oops, I translated the error too :)
make that last line:
print '%s -> %s' % (key, adict[key])
..the book had a lot more information on many topics, which in this case would warrant the extra pages. Plus, I have the 1st edt. of this one (very good intro to Python, btw), and have read some other stuff by Lutz, and he is not verbose. I don't think he suddenly would change his style and pad a good first book with a couple of hundred pages of fluff.
:).
Wouldn't you know it, I just convinced myself to get this edition too
668.5
Excellent example:
1) I prefer the Python example. It's easier to read. And easier to write the first time. That's the reason Python is better than Ruby: when you write code, you get it right the first time more often. And that's such a huge advantage.
Of course, you screwed up. (I assume you wanted to print the value of k rather than the letter k)
2) You used a comprehension in Ruby but not in Python. And adict.items() would have been easier than adict.keys()
To be more fair:
adict = {'key':'val','key2':'val2','key3':3.14}
[sys.stdout.write(k+'-> '+str(v)+'\n') for k,v in adict.items()]
But if I was writing the code, I'd use a for loop rather than a comprehension.
But for penis length competitions, we'll use the latter.
Bryan
actually an enormous game has been written in "stackless" python: EVE online. the reviews of EVE have been mediocre, but most have complimented the game's graphics. it's also an enormous world with all kinds of complex rules. according to the developers, it wouldn't have been possible without python.
i think EVE proves that python is ready for big projects, even when performance is critical.
dude, don't feed the trolls
get lost in the quagmire of lists, arrays, scalars, references, etc.
uh? Care to differentiate between lists and arrays? Or are you trying to spread a little FUD to make it sound more complicated then it is.
Explain how using and referencing extra dimensional data types (list and hashes) are different in Python.
See here:
http://osnews.com/story.php?news_id=5602
C# is the second fastest language in their benchmarks, only trumped by C++, and it is an interpreted language. So your logic falls apart.
Python scores some pretty abysmal benchmarks compared to all the other languages, including Java. So I'd say, it's just slow.
EXCEPT when it comes to using a single character (domino) to solve simultaneous linear equations :)
and what - is the number of characters in a program to convert roman numeral characters to arabic still something along the lines of 34-37 characters?
Of course it beats the prunes out of APL. APL will siphon the cyles out of practically any machine it touches.
List comprehensions are confusing and violate Pythons "one way to do it" philosophy, if you ask me. They are confusing because they are basically multi-argument operators:
...." ??
foo for bar in baz if quz
also like the C ternary operator
foo ? bar : baz
I try and avoid things like this that take more than instant to mentally parse.
PS: if Python is so clear and easy to write why do people constantly say "well, if *I* were writing that code in python, I'd do
yup, and that's exactly why a mediocre language like Python is winning against a horrible language like Perl!
it's a shame really...
Try one of these: AddAll, BookPool, Best Book Buys. Unfortunately, Froogle can't compete this time.
Maybe I am some kind of a mutant or something but the Python example was way easier for me to understand than the Ruby example.
for key,value in adict :
print "%s -> %s" % (key, value)
Votez ecolo : Chiez dans l'urne !
for key,value in adict.items() :
print "%s -> %s" % (key, value)
sorry
Votez ecolo : Chiez dans l'urne !
Wow... Are you writing your posts with a typewriter?
Programming can be fun again. Film at 11.
Same here..
.. that's fine, but Python is half-baked. I'm confused why people say it is so great and elegant. Is it just because it's NotPerl(tm)? (I actually like the whitespace parsing in Python, btw).
I tried Python at first and found it much nicer than Perl. Like many others I was hungry for a non-compiled, object-oriented language which was for large projects, not just quick hacks. Someday, computers will be fast enough so that all our coding is done in these languages.
But immediately the "object model" if you want to call it that got on my nerves. Why "len(list)" and not "list.len()"? Why "'\n'.join(array)" instead of "array.join('\n')"? What's with the simplistic scoping? Why all the underscores? Why "self" everywhere, and why is it so unpythonic to just call it "s" instead? Do I really have to type parantheses all the time? Where are the first-class regexps? Does it make sense that for many built-ins, "foo(obj)" calls "obj.__bar__", why not just use "obj._foo()" directly and eliminate "foo()" from the language.
Lots of other people found it much nicer than Perl, and jumped on the bandwagon
I guess I'm one of those weenies that believes all languages eventually become Lisp or Smalltalk, and any sharp corners that vary from those models will eventually be "filed off". I tried Ruby and discovered it was much more like Smalltalk. Very elegant and easy to write code. And coming from Perl, it has much of the power of Perl but in an object-oriented way. Unfortunately Python stole the thunder and now python has the great docs and 3rd-party libraries, while Ruby lingers and grows slowly.
And Python has the arrogant, Perl-like community now, that thinks jamming list comprehensions and generators into everything makes you "cool". Why do they think it's so cool to reduce the number of lines in a program? I own the "Python cookbook" and find it highly irritating. Rather than solving problems in a single elegant and general way, it presents each author's particular 'leet Python skills, and usually 4-5 different solutions (in a language that claims "one way to do it"). I found it very unhelpful, and again was confused when people said it was such a great book.
Python is moving in the right direction though. My fear is that someday it will be possible to write very elegant code in Python, yet still have to support all the Python 1.5 code out there, so the language will be a huge mess. Some may argue that it is already becoming a mess. I think Guido should come out with Python 3 and make it totally non-backwards compatible.
The poster should not have used a list comprehension to call sys.stdout.write.
My rule of thumb: if I don't need the results of a list comprehension, it's probably best written as a regular for loop. The fact that the original poster used 'sys.stdout.write' when he wanted to print something is a dead-giveaway (print is a statement, which is why it's not valid in the list comp):
This:
[sys.stdout.write(k+'-> '+str(v)+'\n') for k,v in adict.items()]
Could have just as easily been written (more clearly) as:
for k, v in adict.items():
print '%s -> %s' % (k, v)
It took a lot of tries to get that right. Imagine now how hard it would be to debug your program if you only had a tenuous grasp of the language, and some of those incorrect forms didn't produce errors.
The Ruby version is half the length of the Python one, and much more readable. "sys.stdout.write" manages to be both verbose and full of idiosyncratic abbreviations.
[print k+' -> '+v for k,v in adict.items()]
I picked it up a few years ago around the same time I was picking up Java, so I tend to compare it with Java. Initially I used them both for simple applications like XML processing and filtering.
Generally speaking, I liked Python quite a bit, especially the identation delimeting code blocks thing quite a bit, especially the visual cleanness of the code (although this was slightly offset by the need to dereference member variables with "this->"). I found the module system a bit squirrely, especially the execution on load thing.
In the end I ended up gravitation towards Java for larger and more complex projects, because of its larger and highly useful non-proprietary library and frameworks, although Python is no slouch in this department either.
I can understand the parent post's enthusiasm for Python. It's an innovative and fun language. However I'm a bit skeptical about claims for its superiority in productivity. Truly, I can't see where the magic pixie dust is here.
If a Lisp partisan tells me that Lisp is 10x more productive on some applications because of the whole program as data thing, or Lisp's language extensibility, I can understand this whether or not a I choose to agree with it. What I don't see is why an experienced and fairly expert coder should be much if any more productive in Python than Java, since they tend to promote similar garden variety OO architectures.
Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
Not that there are a great many dynamically scoped languages around these days...
That didn't work with Java -- I couldn't even remember that long initialization thingy at the start from sitting to sitting. Freshing up C was to much of a problem, since I was never good enough for it to go subconscious and it takes forever to even say "Hallo World" -- and I have neither the time nor the problems that require such a low level language. Perl looked fun for a while, but two months later I couldn't figure out what I had been trying to do.
So at some point I found Python, and used Learning Python, First Edition as my introduction. If the Second Edition is even close, go for it. Beautiful language, very friendly people on the Tutor list, and if I'm forced to take a few weeks off from the keyboard, I can come right back and still be productive.
No, I will never be a real programmer, let alone a "Hacker", but I am able to get the computer to do the few simple things that I want it to do. Thanks to Guido van Rossum and his cast of thousands for a free, simple but powerful language that lets us mere mortals do just that.
How's that "[n], is that you?" gig working for you?
...
>>> import karmawhore
>>> print karmawhore.firsttimeoffenders?
jalet,
Incidentally, what have you found to be the best ways to code a dynamic website in Python? I know about Zope and have used it a bit, but are there other compelling options?
Please mod this post only if you think others should/n't read this. I have enough ego^H^H^Hkarma. Thanks!
Other than as an amusing tool to utterly confuse any but the most advanced developers, continuations are probably only useful for coroutines, and coroutines are mostly useful for iterator generators, which recent versions of Python have generators nicely packaged in an easy-to-understand syntax (the yield statement).
Continuations are also incredibly useful for massively scalable network applications. They are arguably the best way to write them, in terms of code readability and performance.
There's one major reason I use scheme instead of silly languages like Python or Perl, lack of static typing. Scheme's type predicates are much more flexible.
an ill wind that blows no good
adict = {'key':'val','key2':'val2','key3':3.14}
for k, v in adict.iteritems():
print k, '->', v
I think this is actually more readable than Ruby's "each" function which is a weaker alternative to iteration.
Here's a program I've written in ruby, just today, in about 2 hours.
It generates a graphical waveform from the component harmonics, as well as graphing the first 10 harmonics.
Source Code: http://tylere.com/waveform.rb.txt
Some Examples:
Square Wave
A Phased Sine Wave
Triangular Wave
Sawtooth Wave
TODO: Something witty here...
Regrettably, Tom has chosen to go off-topic to focus on the wrong set of issues - comparing agile language A to agile language B, rather than commenting on the value of the Python book itself, or even (if any off-topic can of worms really must be opened,) commenting on common foes to all lightweight languages (LWLs,) such as the CLR or compile time typing issues that cross-cut a preference for one LWL's syntax or feature set to another
Well well...
If you think Python is so great, then why didn't the Developers of Python develop Python by using Python instead of C?
Huh? What's that? Is that the sound of a black hole sucking us all in?
The real Programmers use C...and they ha^H^H learn to like the pain.
PS: if Python is so clear and easy to write why do people constantly say "well, if *I* were writing that code in python, I'd do ...." ??
Where are python developers "constantly" saying this?
Sure, I've seen it said sometimes. Are there developers of *any* language that don't habitually debate points of style and idiom?
Perhaps you are thinking of C++?
sorry eclectum, you can't use print in a list comprehension. SyntaxError.
The comprehension doesn't add anything to this example. Let's stick with the time-honored:
for k, v in adict.items():
print k+'->'+v
(you can put it on one line if you really want)
Weak typing is the opposite, where a language will implicitly convert between (possibly incompatible) types or will simply allow any operation to occur.
That's not weak typing. That's simply automatic conversion of types in some cases. Weak typing is like that of Forth, where if you add a float to an integer, the BIT PATTERNS are simply added together, as if both of them were integers.
Python is strongly, dynamically typed. If you try to perform an integer operation on a string, it will check this at runtime and raise an exception. It will not perform the operation.
Python will do similar conversions, just not for strings. For example, you can add integers and floating point values without explicit conversions. From a type view, 1 + 1.0 is exactly the same as 1 + "1". So Python is no more strongly typed here than Perl is, though I realize there's a popular compulsion to make out Python to be superior to Perl (which it is in many cases, though this isn't one of them).
But immediately the "object model" if you want to call it that got on my nerves. Why "len(list)" and not "list.len()"? Why "'\n'.join(array)" instead of "array.join('\n')"? What's with the simplistic scoping? Why all the underscores? Why "self" everywhere, and why is it so unpythonic to just call it "s" instead? Do I really have to type parantheses all the time? Where are the first-class regexps? Does it make sense that for many built-ins, "foo(obj)" calls "obj.__bar__", why not just use "obj._foo()" directly and eliminate "foo()" from the language.
:)
.append() loops in most cases. I also love generators and find they are amazing ways to write extremely simple code that yields generic iterators. (Extremely useful for the implementation of __iter*__ methods).
Lets call this the foo indirection.
The foo indirection is useful because it releases the tight coupling between the foo(obj) call, and the obj.__bar__() call.
For example, the int(object) call is implemented by usually calling object.__int__(), but this is not necessarily so.
int is a type whose constructor converts objects to an integer using __int__ or other protocols/methods.
For example, int(some_string, 16) will convert the string to an integer treating it as an ascii representation of a hexadecimal number. The string does not necessarily have __int__ and/or does not necessarily support the same arguments as int.
The foo indirection also allows for later modifications of things like the len() function without modifying the __len__ method protocol.
The foo indirection is exactly the same as the indirection you get when using object[subscript], where that subscript may be an index or a slice. It used to call __getitem__ or __getslice__, which is a messy protocol. Because of this indirection, the messy protocol was now cleaned to __getitem__ which may take an integer index or a slice object index, while still supporting __getslice__.
I guess I'm one of those weenies that believes all languages eventually become Lisp or Smalltalk, and any sharp corners that vary from those models will eventually be "filed off". I tried Ruby and discovered it was much more like Smalltalk. Very elegant and easy to write code.
Python does not try to be Smalltalk, however it is indeed very similar to Lisp in many ways. However, there is a fundumental difference in the philosophies of Lisp and Python. Lisp tries to be the "language of languages", where macros let you variate the language to your specific needs. Python tries to be the "uniform language", where macros would never get in the language because they harm uniformity.
Unfortunately Python stole the thunder and now python has the great docs and 3rd-party libraries, while Ruby lingers and grows slowly.
Fortunatly, if you ask me
And Python has the arrogant, Perl-like community now, that thinks jamming list comprehensions and generators into everything makes you "cool".
I simply find comprehensions more readable than
Why do they think it's so cool to reduce the number of lines in a program? I own the "Python cookbook" and find it highly irritating. Rather than solving problems in a single elegant and general way, it presents each author's particular 'leet Python skills, and usually 4-5 different solutions (in a language that claims "one way to do it").
The number of lines is often a good (perhaps rough) indicator of the number of bugs in the code. Code that's not written does not have bugs. I find the "advanced" generator-using solutions very elegant and general.
Python does not claim there is "one way to do it". Python claims "there should be one obvious way to do it, preferrably only one". There can be more than one obvious way, and there always is more than one way (just not obvious).
I found it very unhelpful, and again was confused when people said it was such a great book.
> rather than commenting on the value of the
> Python book itself
Hmm... I see a book review as a starting point for spawning off discussions - linking to a page discussing Pythons pros and cons seems reasonable.
> commenting on common foes to all
> lightweight languages
Foe, or design choice?
The Army reading list
Maybe not Half Life, but "Severance: Blade of Darkness"'s logic is written in python.
Singularity: a belief in the "God" idea with the "demiurge" relation inverted.
Most of my development deals with internationalisation and support for many languages and scripts. For that reason, I prefer Python, because one can make all internal strings Unicode no longer have to worry about a million character sets. Ruby, on the other hand, lacks support for Unicode. I know the iniciator of Ruby comes from Japan, where because of CJK chauvinism Unicode sadly hasn't caught on yet, but this is the 21st century, and a scripting language without support for Unicode is just unacceptable.
errr, actually, you only need one: Subtract and Branch if Negative
Did you mount a military-grade, variable-focus MASER on an unlicensed artificial intelligence?
I've been using Albatross ( http://www.object-craft.com.au/projects/albatross/ ) and Albatross Extensions ( http://axe.pseudocode.net/ ) on Apache + mod_python.
Perl is great for UNIX scripting, but once you pass a certain point, it begins getting unwieldy (IMHO).
I think this depends a lot on 1) the application and 2) the chosen architecture. I've written some rather largish Perl projects (well, not that large... ~8000 lines) with little difficulty. It really just depends on the choice of design and how well Perl's language features match that design.
Example, the Python cookbook: at the beginning it waxes poetic about how, unlike Perl, in Python there is one clear way to do things.
Then read the recipes. Usually one solution is given in the recipe, then in the discussion about 4-5 more, usually for different Python versions, with/without list comprehensions, with/without objects, nested scopes, or whatever. Maybe the authors are just showing off, who knows. Sometimes they have multiple recipes for the same thing (Singletons, for instance, never mind that you don't *need* singletons in Python, because of modules).
And of course whenever somebody posts a Ruby example, the Pythoneers insist on reducing it to fewer lines or making it more "Ruby-like". Ruby is a more terse language than Python, as a design choice. I find Python becomes more difficult to understand when people try to squeeze lines out of the code. That's not Python style.
What I wish is that 1) they would stop pretending that Python is more elegant than any other language, and drop the "one way to do it" stance and 2) not worry if their code has more lines than other languages. Clarity is in asset that Python seems to be forgetting about as it matures.
"Hello" + 3 will raise an exception in Python, but yield 3 (or "3") in Perl, along with the fact that:
"3" and 3 are indistinguishable in Perl (Might be wrong about this, but for common operations at least, they are indistinguishable),
make Python superior (at least in this specific regard).
I bet you've already seen the answer to your q in the threads here, but for anyone else who missed them:
fredrikj's post on Psyco, and
(another) AC's post mentioning both Psyco and Py2Exe, among other useful things.
Actually what's cool is when you study a language and realize all the control structures and debugger and profiler are completely written in the language itself, or could be, without using any special hooks. That's what blows me away about Lisp (and Ruby to a degree), for instance.
If you have continuations you can create loops, exceptions, even function calls, just with continuations and conditionals.
C will typically convert between incompatible values (pointers and ints, for instance) without an explicit typecast, with certain warnings raised.
/* To emphasize that this is wrong: */
/* Undefined behaviour */
In some cases, incompatible type conversions (mostly between pointers to different types) don't even yield warnings:
char c;
void *a;
int *b;
a = &c;
b = a;
(*b) = 0;
Hell, the mere fact one can incorrectly cast in C makes it weakly typed.
In a strongly typed language, the wrong type may never be applied to wrongly interpret memory bits. This is not true of C, and true of Python. C is weakly typed, Python is strongly typed.
Do you mean to say that you don't indent your code? :)
I tend to believe you ran away screaming before you tried using significant whitespace.
A former colleague and I were discussing this at one stage, which inspired this hack entitled "Audible Code Separator" thereby allowing the bell character (^G) to be used for token separation in Perl scripts. I'll not have any other language stealing Perl's thunder in terms of lack of readability!
How about Lua?
...but there's more brainwork involved. As other posters have mentioned, functional iterators don't get you much if you're just running the function for side effects. "Code should be organized vertically, not horizontally."
:-)
Lua
adict = {key='val', key2='val2', key3=3.14}
for k,v in adict do
print(k.." -> "..v)
end
Why is Lua relevant to this thread? For better or worse, Lua is very small, in a number of dimensions. The number of things you have to remember is small, and you can get by with even fewer. I suppose you could go functional if you wanted to:
foreach(adict, function (k,v) print(k.." -> "..v) end)
If you think of Python as Common Lisp, Lua is like Scheme. Except Lua's in a lot more console games than Scheme.
Incorrect output is an error. How about just checking your output in the interpreter before adding the code to your program?
*gasp*!
People always like to use the % operator, but what's wrong with just:
print k,'->',v
??
Why does this make Python superior to Perl?
This is one of the things I like about Perl.
I hereby inform you that I have NOT been required to provide any decryption keys.
What do you expect from "Hello world 3" + "3"?
I certainly wouldn't expect 0, 3, or 6. I would expect it to either fail, or return "Hello world 33".
Obviously, a language with simple predictable semantics is superior to one with ad-hoc weird semantics.
Slight caveat - Psyco is x86 only. Which is OK if you're not needing a globally redistributable end result. Testing with Plone suggests that by Pysco compiling a few of the more expensive components, you get a 10% speedup.
The only thing you can accurately describe as "Scotch" is a sticky tape made by 3M. And it's
- Almost as powerful and expressive versatile as lisp
- Libraries are powerful and well documented
- Easy to create bindings to C/C++
- Deployment is easy
- Good cross-platform support
- Syntax is easy for uninitiated to decypher
- Large and growing "mindshare"
The last two are related and are actually key.Lisp is really the gold standard of "expressive and versatile" but you just can't jump in and be productive in a day or two like you can in Python.
Perl looks pretty ugly to the uninitiated.
Ruby looks better in a lot of ways but it's not enough better to overcome Python's lead.
I wish I really Dylan was ready. It's a real shame that Gwydion Dylan hasn't made it to production quality yet. It's a classic example of the losing end of worse-is-better. The design gets almost everything "right" which of course makes the initial implementation too difficult.
Do you get wafers with it?
--- Hot Shot City is particularly good.
The problems with significant whitespace has nothing to do with the benefits of code formatting. Everyone knows that proper block indentation improves readability. However, whitespace significance is *incredibly* annoying if things like tabs break (if you've ever edited a Makefile with a naive editor, you'll know *exactly* what I'm talking about, here).
Moreover, it can also make an editor really irritating to use. Case in point, I type this code:
if (condition):
blah
if (condition2): <-- wrong lexical level!
blah
This is Emacs' idea of indenting things. Because there aren't block delimiters, Emacs has no idea that I really want the second "if" statement to be at the same lexical level as the first. Consequently, I'm forced to backspace in order to get things to come out correctly. Plus if I try to auto-indent this code, it's quite possible that it could get it wrong, because there's no way to unabiguously determine the intended scope of the statements in a block.
You get a warning/error (use python -t, ofcourse).
Or if you forget -t, you get an IndentationError or a SyntaxError which is quickly narrowed down to the indentation problem.
Which is insanetly cool, unless you try to actually use that in an actual program. Same as the Turing-complete assembly language which has only one opcode.
actually, i think this is a plus. i have been programming in perl and java for several years. while i love alot of things in java, java is a "one way only" language. try opening a file. try opening a socket. try writing graphics to a control. i understand what java was intended for, but c'mon. i have just picked up python last few weeks. really easy to learn, especially with java/OOP background. probably the coolest thing about python is the toolkit integration. i have got pyGtk, pyQt, as well tkinter up on panther/X11. python cuts dev time down significantly. and it gives yo the freedom and power like perl. it doesn't constrain you. java pisses me off so much sometimes. what i love about coding (since it really isn't vocation) is the challenges to do it differently and better. java has little room for creativity. that's why. at least for me.
My problem? I was perfectly gruntled, until some numbnuts came by and dissed me.
The problems with significant whitespace has nothing to do with the benefits of code formatting. Everyone knows that proper block indentation improves readability. However, whitespace significance is *incredibly* annoying if things like tabs break (if you've ever edited a Makefile with a naive editor, you'll know *exactly* what I'm talking about, here).
There's a fundumental difference between Python's whitespace significance and that of Makefiles. Makefiles dictate where to use tabs, and where to use spaces. Good Python style merely dictates that whatever you use, you use it consistently. Simply don't mix tabs and spaces for indentation. Even naive editors don't have a problem with this.
if (condition):
blah
if (condition2): # wrong lexical level!
blah
When indentation is the lexical level information, obviously you have to adjust it while you write the code. Your assertion that the editor does not indent the code automatically as in other languages is quite silly, because in other languages it knows to indent your code because of the extra information that you type (braces/etc).
Consequently, I'm forced to backspace in order to get things to come out correctly.
As opposed to being forced to press '}' in order to get things to come out correctly with most other languages?
Plus if I try to auto-indent this code, it's quite possible that it could get it wrong, because there's no way to unabiguously determine the intended scope of the statements in a block.
Again, you are trying to apply the concept of auto-indentation, which only makes sense where indentation is redundant information to the braces. Where the indentation is the information, there is no reason to auto-indent because indenting is done instead of, and at a lower cost than typing the curly braces.
Once you stop trying to auto-indent a language where indentation is the one and only specificier of the nesting level, you see that it is quite trivial to unambiguously determine the intended level under which statements go.
I prefer Python to Ruby, but your complaints about Python are right on, IMO.
Your "Python stole the thunder" analysis is not quite right, though, and it relates to why I prefer Python.
Ruby is as old as Python, but Matz wrote Ruby to do his own Japanese *nix work. He focused on his own needs, but made it available to all, so essentially he was focusing on the Japanese *nix community and their needs. The Japanese *nix community, for example, cares far more about handling legacy Japanese data than about handling new, multilingual Unicode data, so Matz's design decisions reflect this local bias, to the detriment of those of us with reverse priorities.
Japanese *nixers are a pretty small, insular community, but that's where Ruby has always been centered. These days, the circle has grown out from that center large enough that there's more for Westerners or non-*nix users to use, but the center is still on Japanese *nix users.
It's that focus that explains a lot of the weaknesses of Ruby as seen from the perspective of a Westerner who cares about cross-platform dev, internationalisation, good and plentiful English docs, a big English-speaking community of experienced users, etc.
I think Matz is a smart, humble guy with real talent when it comes to language design. I like him, and I like Ruby's design more than Python's in many ways, but his focus on Japanese *nix programmers and their local priorities has been a ball and chain around Ruby's ankle that I think explains the more rapid growth of Python worldwide (and Ruby's faster growth in Japan).
"Those who have never entered upon scientific pursuits know not a tithe of the poetry by which they are surrounded."
What kind of job do you have where you can just switch your development language? Even on my personal projects, I have a lot of perl and PHP that I'm trying to migrate to Java (need persistent objects, and sadly, I don't see anything better than EJBs), but it just doesn't seem feasible.
Which languages, "objectively", are the ones to learn?
Though I think the answer is more subjective than you seem to imply, I'm not asking to be argumentative. I'd be interested in what list you would come up with, based on your stated approach, and why you would learn each. As you point out, we don't have time to learn them all, so good advice regarding which few to pick is (potentially) useful.
"Those who have never entered upon scientific pursuits know not a tithe of the poetry by which they are surrounded."
Simply don't mix tabs and spaces for indentation. Even naive editors don't have a problem with this.
Hah! You haven't mixed, say, Vi and Emacs, the two most common editors out there, have you? Depending on the editor settings, Emacs will use spaces, and Vi will always use Tabs. Hell, I haven't done *that* much Python development (relative to other languages I know), and even I have encountered the broken-tabs problem.
When indentation is the lexical level information, obviously you have to adjust it while you write the code.
This is true, it is partly a matter of adaptation. So, I will concede the point.
However, there remains the problem that code can be incorrect, but not necessarily *appear* incorrect (to the developer), since there's no visual markers (other than whitespace) to indicate where the blocks *should* have been. Therefore, if something does get out of place for some reason (and yes, I've had this happen), it isn't always immediately obvious that something's amiss.
I notice everyone wants to use the '->' notation to signify the key->value relationship. Why is this? Could it be because it is less ambiguous than ':'? If so, then why not use that construct in the language, or if it is ambiguous for pointers, use '=>' (as ruby does.) Also, what's a 'def'? A function definition? Why not be more precise, especially if there is already a convention. Python tries too hard to be 'different' in the syntax for being different's sake. That's why I keep giving up on it. Too bad, because I really want something cleaner than Perl or PHP for scripting.
Predictable is subjective. I find Perl's two rules here consistent:
how to invest, a novice's guide
Mainly lots of small projects. Converting one fixed width format to another, things like that. Repetitive to a degree, but not to the point of being able to write a framework, as there is usually special logic involved. I'm also the only programmer at my place employment who writes in modern languages (IE: Not COBOL) so I'm given free reign by and large technically, as long as I can justify WHY X is a valid solution to problem Y.
TODO: Something witty here...
How about just checking your output in the interpreter before adding the code to your program?
Yeah and how about the posters above checking their output in the intepreter before posting to a public forum. Doh!
People always like to use the % operator, but what's wrong with just:
print k,'->',v
The latter is fine, it's just because of the particular implementation of CPython the use of placeholders produces more efficient byte-code.
So, was Iraq better off with Saddam? Ask the Kurds.
Just whatever you do, don't ask the Iraqi's!
Now if we could just get rid of that 'do ... end' and replaces it with, say indentation, you'd have a nice litle language there. :P
Emacs will use spaces, and Vi will always use Tabs.
au FileType python set expandtabNobody codes in python without that in the .vimrc (or the equivalent in .exrc), do they?
Static typing.
An odd reason to make the choice. Given that neither language has static typing. Hmm?
As we can see most of points are serious arguments saying that Scheme is better designed as a language due to its original FP design.
Python has the following advantages to Scheme:
Dispite #1 all other points are weak and don't keep any water.
I call it biased because it's abvious from the above (counting the weakness of the second group arguments) that Scheme is superior, but the comparison author wants Python to look as good as Scheme.
I understand and appreciate when Python language designers bring one by one FP features to the language, but please be honest - Python is still not there yet in terms of having a real power of a FP language.
Having said all that I can add that personally I consider Python as the most power among all other non-FP languages (Python was not originally designed as FP, it's aquired some FP features later).
Due to traditional lack of math education among most of programmers around me I usually have a very hard time to ask them to use FP methods and a FP style. That's why I don't have any chances to ask them to use Lisp or Haskell or ML with me in the same project we work together. As for Python I have such chances: Java programmers find Python's OOP style convinient for them, while Tcl and Perl programmer love that Python is a scripting language.
Don't ask about C and C++ programmers - they are a lost case, when they write applications. Kernel and DB and library programming is fine on C IMHO, but not application logic.
Less is more !
By the way, Lisp vs Python comparison by the famous AI hacker Peter Norvig is way better as it's more objective (less biassed) and it has very important details and very clear examples.
Less is more !
I hate when people throw around the term 'FUD'. Understandably, he just didn't understand Perl, since it isn't that easy for most Python programmers to understand.
I think Perl is pretty interesting because, somehow, the creators have managed to combine the disadvantages of weak and manifest typing. First, due to weak typing within scalars (a term which is completely cryptic unless you know Perl), many things happen unlike you'd think they would (such as "0" == "0.0" returning true), requiring special operators on strings and such. This makes the language hugely overcomplicated (or "expressive", if you like to think of it that way). But then, if you have a vector or hash (also cryptic terms), you need to know that because each of the three main types, scalars, vectors, and hashes, must be prefixed on *every* reference. This is even worse than static typing in a language like C. Unnecessary variable prefixes combined with extremely weak typing make Perl a terrible language for new users.
In Python, lists, tuples and dictionaries (terms from English) are much easier to use. Instead of requiring a prefix on every reference, the object is just created and then you can reference it without a prefix. And references are not necesary due to Python's linking model. Here are some examples of using Python's data types versus Perl's.
dictionary = {'Hi': 1,
'Hello': 2}
hi_value = python_dictionary['Hi']
reference = dictionary
hello_value = reference['Hello']
%dictionary = {"Hi", 1,
"Hello", 2};
$hi_value = $dictionary{"Hi"};
($reference) = %dictionary;
$hello_value = ${$reference}{"Hello"};
I'll let you choose which one is more legible and intuitive. In Python, you don't have to worry about whether things are scalars, hashes, references, or whatever, but if you think that's more readable, then that's fine.
Daniel Ehrenberg
I know people like you... and you all scare me.
MzScheme can be used as a scripting language, and damned if it doesn't have strict syntax. So can many others.
You are looking to slashdot for academic rigor?
It also seems like dynamic typing would hurt the effort as well.
Python, and I believe Ruby as well (at least according to my quick test) are not dynamically typed.
Php is dynamically typed. Python and ruby are "late-binding".
In PHP, you can do:
$a = "1";
$b = "2";
$c = $b/$a;
In python and ruby, and you can't. You have to cast the string first. However, in python and ruby, you can bind any value of any type to any variable, hence "late-binding". In java, you can only bind a value to a variable of a differing type in some situations (i.e. inheritance).
Social scientists are inspired by theories; scientists are humbled by facts.
BTW an indentation consistency checker is part of our build process. It doesn't care if you use all spaces or all tabs, as long as they're not mixed within a file. Then again, this was only required after a time as one or two of the developers were rather sloppy in this respect.
Hell, I'd love to put in a kind of spelling checker as well as those same individuals are also rather atrocious spellers.
One of the things I like best about python is its seamless integration with C. How is ruby in that department? Also, is the standard library getting more complete? I think last time I checked python was a little better there.
But as far as the language itself, ruby is amazing.
Social scientists are inspired by theories; scientists are humbled by facts.
Ruby's C interface is, from what I understand, similar to Python's, ie, quite functional nad integrated, although I haven't really messed with it.
The actual standard lib is smaller, but this has the advantage that the source tarball is maybe 1/3rd the size of pythons (I'm thinking along the lines of 2.5MB vs 8 MB or so). Modules to do just about anything are available at the RAA (Ruby Application Archive) (http://raa.ruby-lang.org)
TODO: Something witty here...
They do have some O'Reilly books at English-language bookshops in Indonesia, but the mark-up is anywhere from 30%-50%.
Michel
Fedora Project Contribut
This is FUD. The standard release at times is far behind ActivePerl in providing bug fixes.
The patches that made ActivePerl 635 were basically released as Perl 5.6.2 (with some portability fixes) almost a year after ActivePerl 635 was released.
Here is a link to a p5p BOF about 5.6.2. I'll quote the interesting part:
Feb 4, 2003: http://downloads.ActiveState.com/ActivePerl/src/5
vs Nov 16, 2003: http://use.perl.org/article.pl?sid=03/11/16/16222
I too prefer Ruby. And as such, it's nice to see Ruby being mentioned more often. Sure the Ruby community is smaller (in the US anyway) than the Python community, but we do seem to be steadily gaining new users (even some Python refugees).
The whole Ruby vs. Python issue is probably mostly a "different strokes for different folks thing". Either is a good choice to learn at this point. Try them both and see which one fits you better. In my case it mostly came down to the indentation- as-syntax issue with Python (often this is referred to as 'whitespace as syntax', but pretty much every language relies on whitespace somewhere, so indentation is more specific). I really strongly disliked Python's indentation-as-syntax 'feature'. I know that many Pythonistas will claim that with the right editor settings it's not problem, but for me not being able to cut&paste code is a deal-breaker (and having important pieces of your code be 'invisible' just doesn't sit well with me). I tried Python for a few days before trying Ruby and was bit a few times by the indentation-as-syntax thing - no thanks (but to each his own).
The culture of the two language communities also seems very different. Ruby's seems more 'free' (for lack of a better word), while Python's is, uh, more, um... well, I'm not wanting to start a flamewar here, but the Python folks do seem a tad bit more, uh, anal.. err, I mean 'uptight' (for lack of a better word).
By 'free' as applied to the Ruby community I mean that while there are some aspects of the language that some might consider 'dangerous' (the fact that classes are always open, for example) and others consider very powerful (I like the fact that classes are always open - it's a powerful feature) the attitude is that you're a grownup and you can figure out how to use these powerful features wisely, we're not going to constrain the language just because some kid might 'hurt himself'.
All this to say that I think that each language appeals to a different sort of person. Python probably tends to appeal to the safety conscious, neat person (and we need people like that, don't get me wrong). While Ruby probably tends to appeal to the more creative "don't cramp my style" type of person. That's not to say that Ruby is 'dangerous' - I'm starting to use it on a commercial project and it's a big productivity booster - just that you probably have to exercise a bit more wisdom when using it.
yep, mixed tabs and spaces is bad. Guido included this on his list of python regrets at Pycon 2003. FWIW, emacs python-mode is fantastic, and vim usually annoys the heck out of me until i remember to set up .vimrc properly.
However, when actually programming in those great functional languages, one often have a hard time deciding whether to use imperative or functional style. Programs in functional style is much prettier, but many data structures (arrays, hashtables) are inherently imperative, so in many places I just have to go the imperative way, which leads to either a mostly imperative program (might as well use Python or Java), or a mixture of functional and imperative stuff which is IMHO a bit slower and somewhat harder to maintain.
To this day the most complex thing I have ever written in Scheme/Lisp/OCaml is an Unlambda interpreter written in OCaml, which is about 20KB of source code. I just can't make more good use of the functional features in more general-purpose code.
PHP as in your example is "weakly typed". Python and Ruby are strongly typed but dynamically typed. "statically typed languages" refers to a language in which the type of everything is known prior to runtime, which is what you call "early-binding".
Hate to reply to my own post, but I found that Ruby does have Proc objects, &xxx parameters, etc. The syntax is still strange though.
The reason do-while() statements are rarely used by me is that a while(1) { ... break ... } statement is more straightforward for my brain, and often ehough there is stuff after the break statement. Actually, in this case I might as well use "goto" statement which can be as clean, but again goto's are easy to read but not straightforward to write.
I once actually wrote an assembly language coroutine setup: it served mainly to connect the write word subroutine of one already working program to the read word subroutine of another one.
your print statement won't run (at least not with
any version of python i'm familiar with).
should read
print k, '->', v
cheers,
b.
check your speling
I meant, imagine if some of those examples didn't produce compiler errors, only incorrect output.
I think it's meant as a guiding principle to be aimed for, rather than a strict dogma to be followed invariably. Otherwise there are plenty of exceptions, like:
I think delimiting strings with both " and ' violates Python's "there's only one way to do it". They are confusing because they are basically both doing the same thing, so one of them is redundant, even if it's very useful to have them in some cases (which is also the case with list comprehensions).
I think that's the parent's point: "Hello world 3" doesn't look like a number, yet Perl treats it as if it were a number.
foo@bar:~$ perl -e 'print "Hello world 3" + "3", "\n"'
3
foo@bar:~$
That falls under the second rule above. The programmer asked for addition. Perl doesn't like to second guess the programmer.
(This attitude isn't limited to Perl. See "I prefer to program as if errors and exceptions cannot occur" by Ron Jeffries on the XP mailing list for a similar view.)
how to invest, a novice's guide
Don't be a dick. The original poster wanted to use -<, that's not 'everyone'. If it was me, I would've used '=', or even just a '-', and a colon would've been equally appropriate. Tryig to twist something like that just makes you look stupid, or desperate to find something to bitch about.
You haven't mixed, say, Vi and Emacs, the two most common editors out there, have you? Depending on the editor settings, Emacs will use spaces, and Vi will always use Tabs. Hell, I haven't done *that* much Python development (relative to other languages I know), and even I have encountered the broken-tabs problem.
:), so I'm concious to it.
Valid point. When I mix editors, I usually explicitly do search-replace on tabs/spaces to unify them all to the same form. I have been burnt once or twice on tabs problems (well, if wasting 5-10 minutes finding a spacing problem once or twice is a burn
However, there remains the problem that code can be incorrect, but not necessarily *appear* incorrect (to the developer), since there's no visual markers (other than whitespace) to indicate where the blocks *should* have been. Therefore, if something does get out of place for some reason (and yes, I've had this happen), it isn't always immediately obvious that something's amiss.
I think you got that backwards.
In languages where indentation is ignored by the compiler, there is a problem. Indentation is for the human readers, while the braces are for the compiler. A human reader is more likely to ignore the braces for the indentation than vice versa. Thus, in C, a human reader might think that an indented code is within some block where in fact it is not:
if(x) {
for(i = 0; i < 10; ++i)
printf("Blah %d\n", i);
x += 10;
}
The above is confusing, while:
if x:
for i in xrange(10):
print "Blah", i
x += 10
does exactly what the reader would expect.
So, that's one example where the C code appears correct but is actually incorrect. Can you show any example of Python code that appears correct but isn't? The whole point of significant indentation is that the human reader and the compiler are reading the same information, and thus code appearance is exactly what will execute.
I meant, imagine if some of those examples didn't produce compiler errors, only incorrect output.
Python, as a rule, doesn't let things pass silently. With Perl this might be more of a concern.
Python also isn't a purely OO language, which I think is one of the really important parts of Python. It uses functions a lot, and those functions are often more clear than an OO approach would be. People in Smalltalk spend too much time creating frameworks, and not enough time getting stuff done -- because the language rewards that. Python is not a conceptually clear language like Smalltalk, but it's way more practical as a result. (Not that I don't like Smalltalk -- I really do, but ultimately Smalltalk was too insular for me)
There are issues with Python, but really not that many. join as a string method is annoying, and magic methods seem somewhat arbitrary, but there's no perfect solution there either. Operators aren't methods, and some form of translation is necessary, in C++, Ruby, or Python. Python's translation isn't particularly bad (and once you know the names, it's very transparent).
I'm sorry, but that's just not true. Sure, any group of programmers is going to make a few puzzles or playfully minimal programs, but in the Python community these are generally presented as toys or novelties. Cleverness is not worshipped, and especially not at the expense of clarity and simplicity. This isn't true in the Python standard library, most third party libraries, nor in comp.lang.python.Of course, people generally ask questions about hard things, because they don't need to ask about the easy things. And some hard things in Python require cleverness, or doing odd things with Python's object model (which is very flexible). Sometimes people want Python to be like whatever language they know best (e.g., C++, Java, Common Lisp, etc), and so people come up with mechanisms to do what they want (and then usually append "but that's not the Pythonic way to do it" and present a clearer way to get the same effect).
The Python Cookbook didn't amaze me either. I'm not sure what would have -- the best documentation is not needing documentation at all, and for what the Python Cookbook covered I didn't really need documentation.
That falls under the second rule above.
Why doesn't it fall under the first rule also? It doesn't look like a number, so operators that operate on numbers should not be able to be used with "hello world 3". The programmer asked for addition on a string, which doesn't make sense because addition is an operation on numbers. What if I try to use + to do addition on a hashtable and an ordered list? Perhaps Perl will permit this too, and gives some very strange result, but surely this is not a good practice to follow in general, though perhaps that's why people say Perl is needlessly complex and a 'write only' language?
Perl doesn't like to second guess the programmer.
Hmmm, I'm not sure this is such a good general principle. Ditto for the link you referenced. Don't programmers sometimes (in many cases, often) ask for stupid things and make mistakes? Woudn't it be nice if the compiler or interpreter informed the programmer of this? Basing a language on the notion that people are infallible seems a bit iffy to me. A better guiding assumption might be that people are fallible and the compiler/interpreter should be on the lookout for mistakes.
Incorrect output doesn't necessarily mean there's an error.
Anyway, now the discussion seems to have shifted a bit more toward the practical, and Guido is talking about Python 3.0 as a real release. It still looks like it's going to be fairly conservative -- which is good for all of us doing real programming in Python -- but some of the stuff like the changed division semantics look like they are going to wait until that release.