Gentlemen, a call to arms!

Paul Makepeace paulm at paulm.com
Mon Oct 16 17:21:59 BST 2006


On 10/16/06, Peter Corlett <abuse at cabal.org.uk> wrote:
> I do sometimes delight in writing compact and slightly-obfuscated Python.

That's the thing, without actually producing some tortuous algorithm
the best you (one) can usually manage is "slightly obfuscated".

> Earlier versions of Python only had lambda for some serious obfuscation

Even lambda's pretty restricted in terms of what you can actually put
in there. Usually the worst that happens is you (one) accidently write
something elegant that makes good use of assigning from/to tuples
(which is nicer than in perl).

> Here's one I use to tidy up /etc/mtab so doing a df on a Linux box running
> LVM gives more useful device names and is less likely to wrap lines:
>
> #!/usr/bin/env python
>
> import re
>
> def parse_fstab_line(line):
>     fields = line.rstrip('\r\n').split('#')[0].split(None)
>     if len(fields) == 0:   return None
>     elif len(fields) != 6: raise "Parse failed!"
>     fields[3] = dict([(i.split('=', 1)+[None])[:2] for i in fields[3].split(',')])
>     fields[4:6] = [ int(i) for i in fields[4:6] ]
>     return fields
       [snip]

See even this I can pretty much get first read through without too much trouble.

I'm not sure if you were deliberately making it a bit harder but those
magic numbers could be easily replaced with a poor man's enum,
(field_name, another_field_name, ...) = range(6)

> def emit_fstab_line(fields):
>     fields = list(fields)
>     def jeq(i, j):
>         if j is None: return i
>         return '='.join((i, j))

Nest subs, you can't even really do that (static) in perl. So it just
got a bit less obfu'ed. D'oh :)

>     fields[3] = ','.join( [ jeq(i, fields[3][i]) for i in fields[3] ] )
>     fields[4:6] = [ str(i) for i in fields[4:6] ]
>     return ' '.join(fields) + '\n'
>
> fstab = [ parse_fstab_line(i) for i in file('/etc/mtab') ]
> for entry in fstab:
>     entry[0] = re.sub(r'^/dev/mapper/(.+)-(.+)$', r'/dev/\1/\2', entry[0])
> fstab.sort(lambda i, j: cmp(i[1], j[1]))

This is more or less the same as idiomatic perl but without the $ signs.

P


More information about the london.pm mailing list