Python: Avoid short circuit evaluation

前端 未结 3 1423
暖寄归人
暖寄归人 2020-12-10 01:10

This is a problem that occured 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

相关标签:
3条回答
  • 2020-12-10 01:52

    You can simply use the binary & operator, which will do a non-short-circuit logical AND on bools.

    if form1.is_valid() & form2.is_valid():
       ...
    
    0 讨论(0)
  • 2020-12-10 01:58

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

    0 讨论(0)
  • 2020-12-10 01:59

    You can use Clever infix hack for defining your own Boolean operators
    aand=Infix(lambda x,y: bool(x) and bool(y))
    1 |aand| 2 will return True instead of 1

    0 讨论(0)
提交回复
热议问题