What is generator.throw() good for?

后端 未结 4 1652
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 19:55

PEP 342 (Coroutines via Enhanced Generators) added a throw() method to generator objects, which allows the caller to raise an exception inside the generato

4条回答
  •  别跟我提以往
    2021-01-30 20:29

    This "answer" is more like a trivia.

    We can (ab)use the generator's throw() to raise Exception inside a lambda, which does not otherwise support the raise statement.

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

    Quoted from https://stackoverflow.com/a/8294654/728675

提交回复
热议问题