0

Here is a simple lambda express

var= lambda x: x*x
print(var(4))

simple I store the lambda object to a variable use the var to complete the math.

  1. My question :

    How do I create function's that use lambda's as keyworded arguments and uses them properly to preform certain tasks

In this code i get TypeError: 'str' object is not callable

    def test1(**kwargs):

        for fart in kwargs:

            print(fart)   #output is == key
            fart(4)   #fart(4)==TypeError

    test1(key=lambda x: x*x)
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219

2 Answers2

2

You are getting this error because kwargs is a dict. In your case, this dict looks like this:

{'key': lambda x: x*x}

So when you iterate over the dict, you are really iterating over the keys, which in the case of kwargs, are strings (and strings are not callable).

If you really want to get at the lambda, then you should access the value within kwargs at that key:

for fart in kwargs:
    print(fart)
    print(kwargs[fart[](4))

Of course, there's an easier way to do this:

for fart, shart in kwargs.items():
    print(fart)
    print(shart(4))
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1

kwargs is a dictionary. Iterating on a dictionary gives you the key values.

Whn you iterate, just use items() or values() if you expect lambda functions for all keys:

for fart in kwargs:
    print(kwargs[fart](4))

or on values:

for fart in kwargs.values():
    print(fart(4))

More reasonably, what you need to call your lambda is to use the key key:

def test1(**kwargs):
    print(kwargs["key"](4))

test1(key=lambda x: x*x)

here it prints 16

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219