On 22/07/10 09:36, Richard Parsons wrote:
I most prefer python.
For fun (and blissfully ignoring the subject line), here's a python variant of Bretts express-data-as-code approach:
mak@yoda:~$ cat >richard.py <<EOM name='Richard Parsons' address='10 Green Hill' EOM
mak@yoda:~$ cat >me.py <<EOM name='mak' EOM
mak@yoda:~$ cat >letter.py <<EOM import sys import me dude = sys.argv[1] dude_module = __import__(dude) print (""" Yo %s! How's things at %s? Love, %s """ % (dude_module.name, dude_module.address, me.name)) EOM
mak@yoda:~$ python letter.py richard
Yo Richard Parsons! How's things at 10 Green Hill? Love, mak
You get some basic data validation: quoting errors will produce a SyntaxError, missing values an AttributeError. There are some limitations: your field names have to be valid identifier names, you don't want to stomp all over built-ins etc. And obviously it's vital that you trust your "data" to not be malicious.
To give the variables in the template some prettier names, you can use python's built-in string Template (see http://docs.python.org/library/string.html#template-strings). It gets a bit trickier because of the identifier limitations, but you could get around that with some key renaming:
from string import Template import sys import me dude = sys.argv[1] dude_module = __import__(dude) myvars = dict([('dude_' + k, dude_module.__dict__[k]) for k in dude_module.__dict__.keys() if not k.startswith('__')]) myvars.update([('me_' + k, me.__dict__[k]) for k in me.__dict__.keys() if not k.startswith('__')]) print Template("""Yo $dude_name! How's things at $dude_address? Cheers $me_name.""").substitute(myvars)
-- Martijn