Can I use anonymous function with "static" variables in Python?

Can anonymous function be used with "static" variables in Python?

for example

lambda x: re.compile(r'foobar').match(x)


not that good because it can recompile every time it is called (if it re

runs out of cache), thank you pointers to the caching mechanism).

I can do this without recompiling:

def f(line):
        f.c = re.compile(r'foobar')
    return f.c.match(line)


How can I do this with a lambda, without recompiling?

And okay, I don't want to use a helper function to use it inside a lambda. The whole point of using lambda is "anonymity". So yes, lambda is anonymous and self-contained.


source to share

1 answer

A common trick is to provide a default value for an argument that you are not going to provide.

lambda x, regexobject=re.compile(r'foobar'): regexobject.match(x)


The default is evaluated when it is defined lambda

, not every time it is called.

Instead of using lambda

, I would just clearly define your regexps

regex1 = re.compile(r'foobar')
regex2 = re.compile(r'bazquux')
# etc


then pass the associated method wherever needed. That is, instead of

somefunction(lambda x, regexobject=re.compile(r'foobar'): regexobject.match(x))





The use case for an anonymous function is one that will only be called once, so it doesn't make sense to bind a name to it. The fact that you are worried about being re.compile

called multiple times indicates that the functions will be called multiple times.



All Articles