Why "flat is better than nested"?
Steven D'Aprano
steve-REMOVE-THIS at cybersource.com.au
Thu Oct 28 03:53:05 EDT 2010
On Wed, 27 Oct 2010 22:45:21 -0700, alex23 wrote:
> Steven D'Aprano <steve-REMOVE-T... at cybersource.com.au> wrote:
>> > Load the source code for the ‘this’ module into a text editor, and
>> > see how many of the maxims it violates.
>>
>> None of them.
>
> I'd say it easily violates the first 3, being neither beautiful,
> explicit nor simple, and especially "Readability counts".
Well, beauty is in the eye of the beholder. Ignore the large,
unattractive rot13ed string literal -- nothing will ever make that
attractive. Or imagine it was a single line. That leaves a simple,
minimalist script:
s = "Clguba"
d = {}
for c in (65, 97):
for i in range(26):
d[chr(i+c)] = chr((i+13) % 26 + c)
print "".join([d.get(c, c) for c in s])
How is that not a thing of beauty? Oh sure, these days you could simply
write
print s.encode('rot13')
and you'd be done, but 'this.py' dates back to Python 2.1 when the rot13
encoding didn't exist.
I suppose one might change the magic constants 65, 97 to chr('A') and
chr('a'), or iterate over string.letters, but I already mentioned them.
As obfuscated code goes, it's about as obfuscated as rot13 applied twice,
and that's the beauty of it.
You say it's not explicit, but where is the implicitness? Is "print
<expr>" not explicit enough for you?
Simple? I'd like to see somebody write it more simply, other than using
the rot13 encoding (which didn't exist when the module was created).
I'm not trying to say that module 'this.py' should be held up as the
paragon of Python modules. It's more of a script than a true module,
which makes importing it for its side-effects (the print statement)
somewhat unusual. But violate the Zen? Hardly.
> The whole thing could be replaced by a single print """The Zen of...""".
But that would miss the point. It's supposed to be light-hearted. Zen is
supposed to be a Mystery (with a capital M). You can't just stumble
across the Zen while grepping the source code. You have to make a
concerted effort to discover it with import this.
But we're over-analysing this. The message in the Zen is serious, but the
medium -- the silly obfuscation, the fake mysticism, the use of koan-like
form -- is light-hearted. It's not a web server, for heaven's sake, it
has five lines of code!
--
Steven
More information about the Python-list
mailing list