I have some code that uses a lambda to enhance the functionality. For backward compatibility reasons, this lambda can take one or two arguments. To handle these cases, I now use except TypeError to differentiate in the calls:

# This should work for both these cases:
# l = lambda x: x+2
# l = lambda x,y: x+y

   value = l(10)
except TypeError:
   value = l(10, 20)

This works, but could this be made better? What if I decide to have three or more arguments for example?


I would move the lambda into a full function. There are some schools of though that lambdas should never be assigned and persisted to variables (the alterative being they're directly passed as arguments.

What your existing code shows is that you'd like the second argument (y) to be optional with a default value of 2 (or is it 20?). Therefore, you could do:

def l(x, y=2):
    return x + y

value = l(10)  # 12
value = l(10, 20)  # 30
  • \$\begingroup\$ Please refrain from answering low-quality questions that are likely to get closed. Once you've answered, that limits what can be done to improve the question, making it more likely that your efforts are wasted. It's better to wait until the question is properly ready before you answer! \$\endgroup\$ Nov 16 '21 at 18:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.