Home > Net >  Using lambda function to switch between different functions in python gives TypeError if invalid fun
Using lambda function to switch between different functions in python gives TypeError if invalid fun

Time:02-03

I recently learned lambda functions and switch case and I'm playing with them to understand better. Here, I'm trying to use lambda function to switch between different functions in python like the following

def fn_a(x,y):
    return (x y) * 2
def fn_b(x,y=0):
    return (x y) * 3

def switch(case):
    return {
        "a":fn_a,
        "b":fn_b,
    }.get(case, lambda: case   " Not Available")

print(switch("a")(2,3))
print(switch("b")(2))
print(switch("c")())

>>> 10
>>> 6
>>> c Not Available

The above works as expected. But if I give print(switch("c")(50)), I get TypeError: switch.<locals>.<lambda>() takes 0 positional arguments but 1 was given. What should I do to make this work and why? Is there a better way to make all the 4 print statements work?

I tried to use lambda and switch statements to switch between functions but I'm unable to make all the mentioned 4 print statements to work.

CodePudding user response:

You can modify the lambda function to take any number of arguments and return Not Available when a case is not available.

def switch(case):
    return {
        "a": fn_a,
        "b": fn_b,
    }.get(case, lambda *args: case   " Not Available")

CodePudding user response:

Welcome to lambdas! Your lambda in question is missing an argument. You can make it handle zero or more arguments using the *args feature like this

lambda *args: case   " Not Available"

This will give the expected value

10
6
c Not Available
c Not Available
  • Related