[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Zen of Python

On Mon, 27 May 2002, Paul Prescod wrote:

> I don't want to pick on Perl but we cannot consider the issue of
> conciseness and flexibility versus readability without comparing these
> two siblings. The two communities have a lot of immigration between them
> so we have the testimonies of real programmers.

<snip many complaints about write-only perl>

I think you're conflating two things here: one is how succinct a language
is, the other is how regular.  Perl is, very much by design, extremely
non-regular.  Perl is all about DWIM: succinctness, yes, but succinctness
gained by having a lot of implicit and very complicated rules. Languages
like Scheme and Smalltalk, on the other hand, are both quite succint and
extremely regular and explicit, far, far, far more so than Python is.  I
strongly believe that their kind of succinctness - perhaps it should be
called terseness - very much improves readability.

An example: there is an idiom in Perl and Ruby for lazily initializing an
element of a hash table.  In Ruby, it looks like this:

dict['foo'] ||= 42

To read this you have to know that this expands to

dict['foo'] = dict['foo'] || 42

which in turn means roughly

if dict['foo'] == nil
  dict['foo'] = 42
  dict['foo'] = dict['foo']

Which isn't even a very good way of doing it, because it's inefficient,
and what if the element had already been explicitly set to nil?

Now, once you know the idiom it's not a big deal, but it throw everybody
for a loop the first time they see it.  Sometimes they can puzzle it out
for themselves, usually they post to the list asking 'wtf is the ||=

In Smalltalk, there is a method called at:ifAbsentPut:.  It looks like

dict at: 'foo' ifAbsentPut: [42].

Anyone reading this code immediately knows what it does, and it does it
efficiently and correctly.  This doesn't use any clever parser
tricks, it just leverages the superior syntax (keyword arguments) and
superior semantics (cheap anonymous functions) of Smalltalk to achieve
equal terseness in a completely regular way.

Lisp has a very similar combination of regularity and power.  I don't know
what the equivalent Lisp idiom would be, if there is one, but you
certainly could write a function that allowed something like
(hash-ref dict 'foo' :if-absent-put (lambda () 42)).

What's the equivalent Python idiom?  My guess is that it will be either
less regular, or less explicit, or both.  I'm not trying to pick on
Python, I'm just trying to point out that there is no simple relationship
between regularity, explicitness, and succinctness; it's entirely possible
to have all three.