[Python-Dev] Making custom patterns for string.Template easier (was: Alternative Implementation for PEP 292)

Brett C. bac at OCF.Berkeley.EDU
Fri Sep 3 22:43:35 CEST 2004


Moore, Paul wrote:

[SNIP]
> Hmm, you'd have to get fancy then, as the "obvious" approach is a
> class attribute
> 
>     id = "[_a-z][_a-z0-9]*"
> 
> but then computing pattern while keeping it as a class attribute is
> harder than I can work out right now.
> 
> Forget it - let's keep it simple until someone shows a real need.
> 

OK, but it isn't *that* bad.  I already have it so that the parts of the 
pattern can at least be separate and it leaves the class alone::

 >>> test = string.Template('This has a ${dotted.thing} in it')
[26527 refs]
 >>> test.braced = "\${(?P<braced>[_a-z][_a-z0-9]*(\.[_a-z0-9]+)?)}"
[26532 refs]
 >>> test % {'dotted.thing': "dotted name"}
u'This has a dotted name in it'
 >>> string.Template('This has a ${dotted.thing} in it') % 
{'dotted.thing': "dotted named"}
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "/Users/drifty/Code/CVS/python/dist/src/Lib/string.py", line 
123, in __mod__
     return self.pattern.sub(convert, self)
   File "/Users/drifty/Code/CVS/python/dist/src/Lib/string.py", line 
119, in convert
     raise ValueError('Invalid placeholder at index %d' %
ValueError: Invalid placeholder at index 11



Making it so that one doesn't have to specify the extra stuff (such as 
braces, $, group name, etc.) would not be hard but could take away from 
the power of it all.  But it does not in any way mess with the class and 
the class' regex is still compiled at class creation time so slowdown 
from anything only happens if someone changes something (did rip out the 
empty __slots__ value, though).

But once again I don't know how useful it would be.  The only thing 
coming off the top of my head is Raymond's Cheetah example of making the 
rules looser for bogus $s.  With this you just need to substitute 
self.bogus.  Nice thing about that is if we change the rules for the 
other pattern groups later on the past code will get that benefit insted 
of being locked into the pattern they probably copied at the time of 
writing and pasted in with their minor tweak.  Also won't lead to errors 
down the road if we add another group to the pattern.

Anyway, I did this partially as an exercise so not a huge deal to me if 
it doesn't make it in, so +0 from me for adding the functionality.

-Brett


More information about the Python-Dev mailing list