Using lambda function to switch between different functions in python gives TypeError if invalid function name is given with argument

Question:

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.

Asked By: cerjq

||

Answers:

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")
Answered By: AboAmmar

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
Answered By: JustLearning