z=0
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:
You can do universal one-liners rather more opaquely with lambdas, as demonstrated at http://sigfpe.blogspot.com/2008/09/on-writing-python-one-liners.html
Using eval is more readable, but scarier.
Post a Comment