Fix Python – Define a lambda expression that raises an Exception


Asked By – Thomas Jung

How can I write a lambda expression that’s equivalent to:

def x():
    raise Exception()

The following is not allowed:

y = lambda : raise Exception()

Now we will see solution for issue: Define a lambda expression that raises an Exception


There is more than one way to skin a Python:

y = lambda: (_ for _ in ()).throw(Exception('foobar'))

Lambdas accept statements. Since raise ex is a statement, you could write a general purpose raiser:

def raise_(ex):
    raise ex

y = lambda: raise_(Exception('foobar'))

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.:

y = lambda x: 2*x if x < 10 else raise_(Exception('foobar'))

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:

type(lambda: 0)(type((lambda: 0).__code__)(

Thanks @WarrenSpencer for pointing out a very simple answer if you don’t care which exception is raised: y = lambda: 1/0.

This question is answered By – Marcelo Cantos

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0