Re: template strings for matching?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Robin Becker

    Re: template strings for matching?

    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,*ar gs,**kwds):
    .... self = dict.__new__(cl s,*args,**kwds)
    .... self.__record = set()
    .... return self
    .... def _record_clear(s elf):
    .... self.__record.c lear()
    .... def __getitem__(sel f,k):
    .... v = dict.__getitem_ _(self,k)
    .... self.__record.a dd(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

Working...