定义一个引发异常的 lambda 表达式 [英] Define a lambda expression that raises an Exception
问题描述
如何编写一个等价于的 lambda 表达式:
How can I write a lambda expression that's equivalent to:
def x():
raise Exception()
不允许出现以下情况:
y = lambda : raise Exception()
推荐答案
给 Python 换肤的方法不止一种:
There is more than one way to skin a Python:
y = lambda: (_ for _ in ()).throw(Exception('foobar'))
<小时>
Lambda 接受语句.由于 raise ex
是一个语句,你可以编写一个通用的 raiser:
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'))
但是如果您的目标是避免使用 def
,这显然并不能解决问题.但是,它确实允许您有条件地引发异常,例如:
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'))
<小时>
或者,您可以在不定义命名函数的情况下引发异常.您只需要一个强壮的胃(以及给定代码的 2.x):
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())
还有一个python3强胃解决方案:
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())
<小时>
感谢@WarrenSpencer 指出一个非常简单的答案,如果您不在乎引发哪个异常:y = lambda: 1/0
.
这篇关于定义一个引发异常的 lambda 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!