2005-04-04

WyPy を読む -- lambda の置き換え

ひきつづき、WyPy 読み。lambda とか reduce を読むのが苦手なので、手続きっぽく書き換えました。おそらくは等価なコードは、以下のとおり。




#!/usr/bin/python

import re

import os

import cgi



d = os.listdir('.')

h = '<a href=wy?'



# BEFORE:

#p,e,g,s=tuple(map(cgi.parse().get,'pegs'))

#

# AFTER:

p = cgi.parse().get('p')

e = cgi.parse().get('e')

g = cgi.parse().get('g')

s = cgi.parse().get('s')



# BEFORE:

#f=lambda s:reduce(lambda s,(r,q): re.sub('(?m)'+r,q,s), (('\r',''),('([A-Z][a-z]+){2,}',lambda m:('%s'+h+'e=%s>?</a>',h+'g=%s>%s</a>')[m.group(0) in d]%((m.group(0),)*2)),('^{{$','<ul>'),('^# ','<li>'),('^}}$','</ul>'),('(http:[^<>"\s]+)',h[:-3]+r'\1>\1</a>'),('\n\n','<p>')),s)

#

# AFTER:



def findAndReplace(string, (pattern, repl)):

return re.sub('(?m)'+pattern, repl, string)



def replaceWikiWordWithLink(m):

if m.group(0) in d:

template = h+'g=%s>%s</a>'

else:

template = '%s'+h+'e=%s>?</a>'

return template % ((m.group(0),)*2)



def filter(s):

"""

s = findAndReplace(s, ('\r',''))

s = findAndReplace(s, ('([A-Z][a-z]+){2,}', replaceWikiWordWithLink))

s = findAndReplace(s, ('^{{$','<ul>'))

...

"""

return reduce(findAndReplace,

(('\r',''),

('([A-Z][a-z]+){2,}', replaceWikiWordWithLink),

('^{{$','<ul>'),

('^# ','<li>'),

('^}}$','</ul>'),

('(http:[^<>"\s]+)',h[:-3]+r'\1>\1</a>'),

('\n\n','<p>')),

s)





# BEFORE:

#o,g=lambda y:(y in d and cgi.escape(open(y).read()))or'',(g or p and[open(p[0].strip('./'),'w').write(s[0])or p[0]]or[0])[0]

# AFTER:



def o(y):

if y in d:

return cgi.escape(open(y).read())

else:

return ''



if g:

g = g[0]

elif p:

open(p[0].strip('./') ,'w').write(s[0])

g = p[0]

else:

g = 0





# BEFORE:

#print'Content-Type:text/html\n\n'+(s and', '.join([f(n)for

#n in d if s[0]in o(n)])or'')+(e and'<form action=wy?p=%s method=POST><textarea\

# name=s rows=8 cols=50>%s</textarea><input type=submit></form>'%(e[0],o(e[0]))

#or'')+(g and'<h1>%ss=%s>%s</a>,%se=%s>edit</a></h1>'%(h,g,g,h,g)+f(o(g))or'')

#

# AFTER:



print 'Content-Type:text/html\n\n'



if s:

print ', '.join([filter(n) for n in d if s[0]in o(n)])

else:

print ''



if e:

print '<form action=wypy.cgi?p=%s method=POST>' % e[0]

print '<textarea name=s rows=8 cols=50>%s</textarea>'% o(e[0])

print '<input type=submit>'

print '</form>'



if g:

print '<h1>%ss=%s>%s</a>,%se=%s>edit</a></h1>'%(h,g,g,h,g)

print filter(o(g))