Gentlemen, a call to arms!
Peter Corlett
abuse at cabal.org.uk
Mon Oct 16 16:46:22 BST 2006
On Mon, Oct 16, 2006 at 02:45:24PM +0100, Dave Cross wrote:
[...]
> But Python can't possibly be hard to read. It has all that enforced
> whitespace. Or have Python programmers been lying to us all along?
On average, Python possibly has the edge on being readable if it's written
by somebody who knows what they're doing, but when the usual problem with
badly-written code is the structure of the whole program rather than
individual lines of code, this is rather moot.
I do sometimes delight in writing compact and slightly-obfuscated Python.
Earlier versions of Python only had lambda for some serious obfuscation
potential, but now it has list comprehensions with optional conditional
clauses - and they can be nested - lambda has fallen into second place for
crack-induced-Python.
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
def emit_fstab_line(fields):
fields = list(fields)
def jeq(i, j):
if j is None: return i
return '='.join((i, j))
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]))
file('/etc/mtab', 'w').writelines( [emit_fstab_line(i) for i in fstab] )
More information about the london.pm
mailing list