I'm confused about setting a custom delimiter for Python string Templates. I saw a tutorial video that said to use a custom subclass. So I did and it worked:
from string import Template
class MyTemplate(Template):
delimiter = '#'
d = {'key':'value'}
t = MyTemplate('key is #key')
print(t.substitute(d))
#prints "key is value" as expected
So I was thinking, if all I have to do is change a class variable on Template, then shouldn't the following work as well?
from string import Template
Template.delimiter = '#'
d = {'key':'value'}
t = Template('key is #key')
print(t.substitute(d))
#prints "key is #key", but why?
I thought that maybe I had to create a subclass for some reason. So I figured I would write a subclass, but I would allow for the delimiter to be set:
from string import Template
class MyTemplate(Template):
@classmethod
def setDelim(cls, delim):
cls.delimiter = delim
MyTemplate.setDelim('#')
d = {'key':'value'}
t = MyTemplate('key is #key')
print(t.substitute(d))
#prints "key is #key", because it is still looking for '$' as delimiter
I confirmed this behavior in both Python2 and Python3. In all three examples the class variable delimiter was properly set but only in the first example did it actually work. Can anyone explain this please?