RND in Python
I have redone my RND template in Python.
The code looks like this: import re
RND_MATCHER = re.compile(r'%\[(?P<name>[A-Za-z0-9_|.])\]')
def RND(tmpl, ns):
def convert(mo):
sp = mo.group('name').split('|')
name = sp[0]
filters = sp[1:]
if ns.has_key(name):
cnt = ns[name]
for f in filters:
cnt = ns[f](cnt)
else:
cnt = mo.group(0)
return str(cnt)
return RND_MATCHER.sub(convert, tmpl)
An example of usage: text = '<a href="%[link]">%[value|parseInt]</a>'
ns = {'link': 'http://amix.dk', 'value': 5.5,
'parseInt': lambda x: int(x)}
print RND(text, ns)
Compare it to the JavaScript version: function RND(tmpl, ns, scope) {
scope = scope || window;
var fn = function(w, g) {
g = g.split("|");
var cnt = ns[g[0]];
for(var i=1; i < g.length; i++)
cnt = scope[g[i]](cnt);
if(cnt == 0 || cnt == -1)
cnt += '';
return cnt || w;
};
return tmpl.replace(/%\(([A-Za-z0-9_|.])\)/g, fn);
}
Python version is way more cleaner.
JavaScript
·
Python
•
27. Dec 2006
|
|