Can I have anonymous function with "static" variables in Python?
For example
lambda x: re.compile(r'foobar').match(x)
is not so great, because it may recompile every time it is called (if re runs out of cache - thank you responders for pointing out the cache mechanism).
I can do this without recompiling:
def f(line):
try:
f.c
except:
f.c = re.compile(r'foobar')
return f.c.match(line)
How to do it with a lambda, without recompiling?
And well, I don't want to use a helper function, to use inside the lambda. The whole point of using lambdas is "anonymity". So yes the lambda is anonymous, and self-contained.
relibrary has a caching mechanism, so your regex should not be compiled each time function is called.remodule internally caches 100 regexes, so if you aren't using more than 100 patterns you won't see any significant performance gain from doing thisre.compileas an example)import re, you could set the MAXCACHE to whatever you like