How can I write a lambda expression that’s equivalent to:
def x():
raise Exception()
The following is not allowed:
y = lambda : raise Exception()
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is more than one way to skin a Python:
Lambdas accept statements. Since
raise exis a statement, you could write a general purpose raiser:But if your goal is to avoid a
def, this obviously doesn’t cut it. It does, however allow you to conditionally raise exceptions, e.g.:Alternatively you can raise an exception without defining a named function. All you need is a strong stomach (and 2.x for the given code):
And a python3 strong stomach solution:
Thanks @WarrenSpencer for pointing out a very simple answer if you don’t care which exception is raised:
y = lambda: 1/0.