template strings for matching?

Robin Becker robin at reportlab.com
Thu Oct 9 09:29:52 EDT 2008


Joe Strout wrote:
> Catching up on what's new in Python since I last used it a decade ago, 
> I've just been reading up on template strings.  These are pretty cool!  
> However, just as a template string has some advantages over % 
> substitution for building a string, it seems like it would have 
> advantages over manually constructing a regex for string matching.
> 
> So... is there any way to use a template string for matching?  I 
> expected something like:
.......

you could use something like this to record the lookups

 >>> class XDict(dict):
... 	def __new__(cls,*args,**kwds):
... 		self = dict.__new__(cls,*args,**kwds)
... 		self.__record = set()
... 		return self
... 	def _record_clear(self):
... 		self.__record.clear()
... 	def __getitem__(self,k):
... 		v = dict.__getitem__(self,k)
... 		self.__record.add(k)
... 		return v
... 	def _record(self):
... 		return self.__record
...
 >>> x=XDict()
 >>> x._record()
set([])
 >>> x=XDict(a=1,b=2,c=3)
 >>> x
{'a': 1, 'c': 3, 'b': 2}
 >>> '%(a)s %(c)s' % x
'1 3'
 >>> x._record()
set(['a', 'c'])
 >>>

a slight modification would allow your template match function to work even when 
some keys were missing in the dict. That would allow you to see which lookups 
failed as well.
-- 
Robin Becker




More information about the Python-list mailing list