Confusion about dictionaries - keys use value or identity?
Nick Perkins
nperkins7 at home.com
Sun Jul 8 22:24:38 EDT 2001
"Roy Smith" <roy at panix.com> wrote in message
news:roy-2F9DAF.19464308072001 at news1.panix.com...
> So, here's my plan. I was thinking that I might write a thin wrapper
> around the re class which kept a cache of regexes it had compiled.
> myRe.match would take the passed-in regex, look it up in the cache, and if
> it found it, just use the cached compiled version. I figure it would be
> very close to the speed of storing the pre-compiled versions in the
> mainline code, as shown above, but still have the convenience and
> comprehensibility of keeping the regex string at the place where it's
used.
sounds like a plan, something like this:
class matcher:
def __init__(self):
self.compiled = {}
def match(self,pattern,data):
if compiled.has_key(pattern):
comp = self.compiled[pattern]
else:
comp = re.compile(pattern)
self.compiled[pattern] = comp
return comp.match(data)
..it reminds me of a general purpose function i use:
def memoize(fn):
results={}
def mem(*args):
if results.has_key(args):
return results[args]
else:
result = fn(*args)
results[args]=result
return result
return mem
This needs nested scopes.
It will wrap any function that takes hashable arguments.
It is good for functions that do a lot of work,
and are frequently called with the same args.
( I suppose it won't work with kwd args.. )
More information about the Python-list
mailing list