Define a lambda expression that raises an Exception

后端 未结 6 656
失恋的感觉
失恋的感觉 2020-12-02 06:51

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

def x():
    raise Exception()

The following is not allowed:

y =         


        
6条回答
  •  盖世英雄少女心
    2020-12-02 07:48

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

    type(lambda:0)(type((lambda:0).func_code)(
      1,1,1,67,'|\0\0\202\1\0',(),(),('x',),'','',1,''),{}
    )(Exception())
    

    And a python3 strong stomach solution:

    type(lambda: 0)(type((lambda: 0).__code__)(
        1,0,1,1,67,b'|\0\202\1\0',(),(),('x',),'','',1,b''),{}
    )(Exception())
    

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

提交回复
热议问题