Home > Software engineering >  Get the contents of lambda in python
Get the contents of lambda in python

Time:10-29

I define the following variables:

index = 1 
val = 0

I create the following function:

f = lambda a: a[index] == val

Later on, I would like to see the content. I would like to get the index = 1 and the val = 0. I use inspect.getsource(f). However, this gives me:

'f = lambda a: a[index] == val\n'

I was hoping to get the value of index and val.

CodePudding user response:

you could modify the output of lambda in order to save the three element you want (I mean here val , index , and a[index] == val .So, you could do the following :

index = 1 
val = 0
f = lambda a: (a[index] == val,index,val)

let's suppose that you give the function an argument L , then when you want to get the val you do f(L)[2] and index is equal to f(L)[1],then val is equal to f(L)[0]

CodePudding user response:

Turns out you can do this (at least on Python 3.9):

def get_closure_values(f):
    return {
        name: cell.cell_contents
        for (name, cell) in zip(f.__code__.co_freevars, f.__closure__)
    }


def make_fun(index, val):
    return lambda a: a[index] == val


f = make_fun(index=84, val=99)
print(get_closure_values(f))

This prints out

{'index': 84, 'val': 99}

It does peek into interpreter internals, so it might break on you.

  • Related