pythonlambdacode-inspection

How to get the code of just a lambda argument?


In the following example code, inspect.getsource(lambda_argument) seems to include the source code of the function call surrounding the definition of the lambda. How can I prevent that?

import inspect

def fun_of_lambda(lambda_argument):
    print(inspect.getsource(lambda_argument))

fun_of_lambda(lambda x, y, z: x + y + z)

Output:

fun_of_lambda(lambda x, y, z: x + y + z)

Previous version of the question:

import inspect

def decorator_with_lambda(lambda_argument):
    def decorator(inner_fun):
        print("Printing lambda_argument ...")
        print(inspect.getsource(lambda_argument))
        return inner_fun
    return decorator

@decorator_with_lambda(lambda: True)
def function() -> None:
    pass  # This should not be printed as part of lambda_argument!

function()

Output:

Printing lambda_argument ...
@decorator_with_lambda(lambda: True)
def function() -> None:
    pass  # This should not be printed as part of lambda_argument!

Update: dill.source seems to have the same issue, and I have reported https://github.com/uqfoundation/dill/issues/583.


Solution

  • What I've found in other cases is dill.source can't get the source of "unnamed" lambdas. If you name them (i.e. give them an entry in the namespace), then dill.source works as expected. The same seems to apply in your case:

    >>> foo = lambda : True
    >>> import dill.source
    >>> def decorator_with_lambda(lambda_argument):
    ...     print("Printing lambda_argument ...")
    ...     print(lambda_argument)
    ...     print("Printing source of lambda_argument ...")
    ...     print(dill.source.getsource(lambda_argument))
    ...     def decorator(inner_fun):
    ...         return inner_fun
    ...     return decorator
    ... 
    >>> @decorator_with_lambda(foo)
    ... def function() -> None:
    ...   pass
    ... 
    Printing lambda_argument ...
    <function <lambda> at 0x100b903a0>
    Printing source of lambda_argument ...
    foo = lambda : True
    
    >>>