string.Template.delimiter cannot be overriden?

Raymond Hettinger python at rcn.com
Tue Jun 24 11:17:03 EDT 2008


[kretik]
>> I've been trying to coax this class to use something other than the
> >> default '$' but it seems setting it to something else has no discernible
> >> effect. Is it necessary to inherit from the class to do this?

[raymond]
> > Yes, subclassing is the intended way to produce variants of Template
> > with a different delimiter.

[gabriel]
> Just out of curiosity, why was it done that way?
> I'd say the "obvious" way to change the default delimiter would be to set  
> an instance attribute - so I guess this was a deliberate decision, but I  
> can't figure out why it is better this way...

IIRC, Barry and Tim came-up with the metaclass because the delimiter
and
pattern decisions are less granular than the creating of individual
templates.
Typically, the former decision is made once per application, but there
may
be thousands of template instances.

An earlier version of the API looked like this:

   s = Template('Move %piece to %position', delimiter='%')
   t = Template('%source takes %target', delimiter='%')

The repeated need to set the delimiter for every template was slow and
error-prone.

The newer API is:

    class PercentTemplate(string.Template):
        delimiter = '%'
    s = PercentTemplate('Move %piece to %position')
    t = PercentTemplate('%source takes %target')

So, basically it was just a factoring decision.

Instead of using a metaclass, one other possible choice would have
been to use a factory function:

    PercentTemplate = template_maker(delimiter='%')
    s = PercentTemplate('Move %piece to %position')
    t = PercentTemplate('%source takes %target')

Raymond



More information about the Python-list mailing list