Python:避免短路评估 [英] Python: Avoid short circuit evaluation
问题描述
这是在处理Django项目时出现的一个问题.这与表单验证有关.
This is a problem that occured to me while working on a Django project. It's about form validation.
在Django中,当您拥有提交的表单时,可以在相应的表单对象上调用is_valid()
来触发验证并返回布尔值.因此,通常在视图函数中会包含类似的代码:
In Django, when you have a submitted form, you can call is_valid()
on the corresponding form object to trigger the validation and return a Boolean value. So, usually you have code like that inside your view functions:
if form.is_valid():
# code to save the form data
is_valid()
不仅可以验证表单数据,还可以向表单对象添加错误消息,然后可以向用户显示错误消息.
is_valid()
not only validates the form data but also adds error messages to the form object that can afterwards be displayed to the user.
在一页上,我同时使用两种形式,并且还希望仅当两种形式均包含有效数据时才保存数据.这意味着在执行代码保存数据之前,我必须在两种形式上都调用is_valid().最明显的方法:
On one page I use two forms together and also want the data to be saved only if both forms contain valid data. That means I have to call is_valid() on both forms before executing the code to save the data. The most obvious way:
if form1.is_valid() and form2.is_valid():
# ...
由于逻辑运算符的短路评估而无法工作.如果form1无效,则将不评估form2,并且将丢失其错误消息.
won't work because of the short circuit evaluation of logical operators. If form1 is not valid, form2 will not be evaluated and its error messages would be missing.
那只是一个例子.据我所知,没有像其他语言(例如Smalltalk)那样贪婪地替代and
/or
.我可以想象这个问题会在不同的情况下发生(不仅在Python中).我能想到的解决方案都是笨拙的(嵌套的ifs,将返回值分配给局部变量并在if语句中使用它们).我想知道解决此类问题的Python方法.
That's only an example. As far as I know, there is no greedy alternative to and
/or
as in other languages (i.e. Smalltalk). I can imagine that problem occurring under different circumstances (and not only in Python). The solutions I could think of are all kind of clumsy (nested ifs, assigning the return values to local variables and using them in the if statement). I would like to know the pythonic way to solve this kind of problems.
提前谢谢!
推荐答案
诸如此类的事情
if all([form1.is_valid(), form2.is_valid()]):
...
在一般情况下,可以使用列表理解,以便预先计算结果(与在此上下文中通常使用的生成器表达式相反).例如:
In a general case, a list-comprehension could be used so the results are calculated up front (as opposed to a generator expression which is commonly used in this context). e.g.:
if all([ form.is_valid() for form in (form1,form2) ])
这也可以很好地扩展到任意数量的条件...唯一的不足是,它们都需要通过"and
"而不是if foo and bar or baz: ...
进行连接.
This will scale up nicely to an arbitrary number of conditions as well ... The only catch is that they all need to be connected by "and
" as opposed to if foo and bar or baz: ...
.
(对于非短路or
,可以使用any
代替all
).
(for a non-short circuiting or
, you could use any
instead of all
).
这篇关于Python:避免短路评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!