Skip to content
Advertisement

Get source function of lambda expression with captured variable

Having a lambda function that uses a regex:

JavaScript

I would like to retrieve the source function including its pattern for error reporting. The expected output would be something like: func = lambda x: re.fullmatch("black.*", x)

Knowing of the inspect module and the function getsource, I managed to solve part of my problem, but the pattern variable is not evaluated:

JavaScript

which yields func = lambda x: re.fullmatch(pattern, x). How can I get the concrete pattern that was captured by the function as well?

Advertisement

Answer

I’m not sure what you’re looking for exactly, but I think there are several ways to achieve what you want.

For example, you could store the pattern inside the lambda function object that you return, or update its docstring:

JavaScript

Using either of this options, the used pattern is still available in the function object so it can be used for error reporting. Note that this is bit hackish, and I’m not sure if this might cause problems in the long run.

By the way: assigning a lambda expression is an anti-pattern (see pycodestyle/flake8 rule E731 and/or PEP-8). You could just as well define and return a function:

JavaScript

I think a nicer and more Pythonic solution is to create a callable object, which could be used as a function but also incorporates the original pattern:

JavaScript

Finally, you could also use functools.partial, which has roughly the same effect as above solution, but using the standard library instead of a custom class. In this case the pattern is stored as args[0] inside the returned object:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement