best Template module

Alex Martelli Alex.Martelli at think3.com
Fri Jan 14 05:30:39 EST 2000


Otis Gospodnetic writes:

> Could anyone recommend a good 'Template module'?
> 
> Template module - a module that will let me create a plan text/HTML
> file with some special markup/tags that I can then replace by some text
> values from within my Python code
> 
> good - fast execution and not too complex :)
> 
> 
Shorn of the 'statement-level' functionality (conditionals and loops),
this is what my smartcopy.py boils down to:

import sys

class copier:
    "Smart-copier class"
    def __init__(self, regex, dict, ouf=sys.stdout):
        "Initialize self's data fields"
        self.regex = regex
        self.globals = dict
        self.ouf = ouf
    def copy(self, inf=sys.stdin, block=None):
        "Copy a file, or any block of lines, expanding expressions"
        if not block: block = inf.readlines()
        def repl(match,self=self):
            "return the eval of a found expression, for replacement"
            return '%s' % eval(match.group(1),self.globals)
        for line in block:
	      self.ouf.write(self.regex.sub(repl,line))


I don't think it gets much simpler than this:-).  Typical use:

import smartcopy
import re

# we choose to bracket embedded expressions between '@...@'
rexp=re.compile('@([^@]+)@')

# define the variables on which the bracketed expressions work
dict={ 'x': 2.3, 'y': 4.5, 'z': 6.7 }

# let output stream default to standard output
copy=smartcopy.copier(rexp, dict)

# stdin to stdout with embedded-expression expansion
copy.copy()


E.g. if standard input is

	@ x @ + @ y @ = @ x+y @

standard output becomes

	2.3 + 4.5 = 6.8


Of course, this could be factored very differently depending
on needs -- I needed arbitrary markers for embedded
expressions to make sure of no conflict with the syntax
for the files being transformed, and for my specific needs
I wanted to fix such markers, and the dictionary for the
expressions' evaluation, but then have the possibility of
processing several input files (or just blocks of lines) onto
a single output stream, in sequence.


I'm sure much more professional and general template
facilities exist, but since the task is so simple in Python
it may still be wortwhile having a small, simple module to
factor and tune to specific needs.

(My full 'smartcopy' module adds embedded Python
_statements_, basically to allow conditionals and loops,
but that does make it a tad more complex:-).


Alex





More information about the Python-list mailing list