Zanndorin
Zanndorin

Reputation: 370

Getting a return value from Lambda python

I'm trying to check if my lambda function is correctly working

rule_defs = {
'and': lambda r: (lambda d, r1, r2: match_rule(r1, d) and match_rule(r2, d),
                  [compile_rule(r[1]), compile_rule(r[2])])}

But when I try to run it

('and', 'a', 'a')

it just shows me something similiar of this

<function <lambda> at 0x023C68F0>, ['a', 'a']

Which as I understand is that i send in ['a'.'a'] into lambda d from which I would like a return value similar to True

Am I misunderstanding something basic?

EDIT:

The calling itself is not the problem but the return value being:

function at 0x023C68F0>, ['a', 'a']

instead of a value (i.e. True) and I'm not sure if that is the fault of my calling or the function itself

The call is done with a "help function"

calling(input)
    return rule_defs[input[0]](input)

(Python 2.7.X)

Upvotes: 0

Views: 5947

Answers (3)

Anand S Kumar
Anand S Kumar

Reputation: 90889

Firstly, if you want your inner function to produce a tuple, you should also add another '(' after starting the inner lambda and close it just before.

Example -

rule_defs = {
'and': lambda r: (lambda d, r1, r2: (match_rule(r1, d) and match_rule(r2, d), [compile_rule(r[1]), compile_rule(r[2])]))}

Or if you were doing it correctly, and outer lambda intended to return a tuple of (lambda, list) , then to call the inner lambda use rule_defs['and'](<parameter>)[0](<parameters>)

When defining lambda within a lambda , you have to call first lambda with () and then again the second lambda with () .

So in your case , you would call your function with -

rule_defs['and'](r)(d, r1, r2)

Or you can assign it to a variable and then call that variable with the double paranthesis.

Example I tested with -

>>> rule_defs = { 'and': lambda r: (lambda d ,r1: print(d))}
>>> rule_defs['and'](1)(2,3)
2

Upvotes: 1

LittleQ
LittleQ

Reputation: 1925

Here is your code:

rule_defs = { # define a dict
    'and': lambda r: ( # `lambda r` return a tuple: (lambda, list)
        lambda d, r1, r2: match_rule(r1, d) and match_rule(r2, d),
        [compile_rule(r[1]), compile_rule(r[2])]
    )
}

You should call your function by rule_defs['and'](r)[0](d, r1, r2) In your case, it would be rule_defs['and'](r)[0]('and', 'a', 'a')

rule_defs['and'] will get the function object lambda r: (...)

rule_def['and'](r) will call the lambda r function, and get the returned tuple

rule_def['and'](r)[0] get the index(0) of the returned tuple, e.g. function object lambda d, r1, r2

rule_defs['and'](r)[0](d, r1, r2) will call the lambda d, r1, r2 function

Upvotes: 0

Klaus D.
Klaus D.

Reputation: 14369

You have to get your lamba expression and then call it:

l = rule_defs['and']
l(d, r1, r2)

Replace the arguments with the value of your choice, then you will get the return value of the lambda function.

You can also do it at once:

rule_defs['and'](d, r1, r2)

Upvotes: 0

Related Questions