Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - How to prevent short-circuit evaluation?

This is a problem that occurred to me while working on a Django project. It's about form validation.

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() not only validates the form data but also adds error messages to the form object that can afterwards be displayed to the user.

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():
    # ...

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about something like:

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

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

(for a non-short circuiting or, you could use any instead of all).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...