Wednesday, October 8, 2008

Paging Captain "Ya know, that's really pretty obvious"

Occasionally, it's useful to be able to write a one-line script (it's especially handy for pasting into IRC channels). Python's one-line capabilities are somewhat limited though. Statement lists (see the offical grammer) are always terminated by a newline. Thus, it's impossible to directly express the following snippet as a single line:

for x in range(5):
   z += x
print z

Of course, there are a vast number of ways to achieve the same effect using the constructs that can be placed on a single line, and, other than showing off, there's usually very little need to coerce something to be a single line.

Today, however, it occurred to me that it's also possible to abuse eval for this (I don't know why this only struck me today), leading to:

python -c 'eval(compile("z=0\nfor x in range(5):\n z+=x\nprint z", "test", "exec"))'

While not exactly readable, I think combination of eval, compile + a one-liner is just too amusing to ignore. I'm sure that eventually, somewhere, I'll be able to convince myself that this trick will be just what I need.

1 comment:

jerith said...

You can do universal one-liners rather more opaquely with lambdas, as demonstrated at

Using eval is more readable, but scarier.