pythonpep8demorgans-law

Is De Morgan's Law Pythonic?


Which of the following if statements is more Pythonic?

if not a and not b:

OR

if not (a or b):

It's not predicate logic so I should use the Python key words because it's more readable right?

Is the later solution more optimal than the other? (I don't believe so.)

Is there any PEP-8 guides on this?

Byte code of the two approaches (if it matters):

def func1():
    if not a and not b:
        return   
    
def func2():
    if not (a or b):
        return
In [49]: dis.dis(func1)
  2           0 LOAD_GLOBAL              0 (a)
              3 UNARY_NOT           
              4 JUMP_IF_FALSE           13 (to 20)
              7 POP_TOP             
              8 LOAD_GLOBAL              1 (b)
             11 UNARY_NOT           
             12 JUMP_IF_FALSE            5 (to 20)
             15 POP_TOP             

  3          16 LOAD_CONST               0 (None)
             19 RETURN_VALUE        
        >>   20 POP_TOP             
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        

In [50]: dis.dis(func2)
  2           0 LOAD_GLOBAL              0 (a)
              3 JUMP_IF_TRUE             4 (to 10)
              6 POP_TOP             
              7 LOAD_GLOBAL              1 (b)
        >>   10 JUMP_IF_TRUE             5 (to 18)
             13 POP_TOP             

  3          14 LOAD_CONST               0 (None)
             17 RETURN_VALUE        
        >>   18 POP_TOP             
             19 LOAD_CONST               0 (None)
             22 RETURN_VALUE        

Solution

  • I'd say whichever is easier for you to read, depending on what a and b are.