How to create an 'empty if statement' in python

后端 未结 4 959
别那么骄傲
别那么骄傲 2020-12-05 17:45

It\'s very common in C: hacking \'empty if statement\' like this:

if(mostlyhappencondition)
    ;#empty statement
else{
    dosomething;
}

4条回答
  •  广开言路
    2020-12-05 18:19

    There is a performance improvement if there isn't an else case in the "if", since the bytecodes don't pass execution into the "if" case.

    Here's some functions and the output of dis.dis(foo)

    The following sample app:

    def foo(x):
        if x:
            pass
        else:
            return x+2
    

    Disassembles to:

    5           0 LOAD_FAST                0 (x)
                3 POP_JUMP_IF_FALSE        9
    
    6           6 JUMP_FORWARD             8 (to 17)
    
    8     >>    9 LOAD_FAST                0 (x)
               12 LOAD_CONST               1 (2)
               15 BINARY_ADD          
               16 RETURN_VALUE        
          >>   17 LOAD_CONST               0 (None)
               20 RETURN_VALUE        
    

    The following

    def foo(x):
        if not x:
            return x+2
    

    Disassembles to:

    11           0 LOAD_FAST                0 (x)
                 3 POP_JUMP_IF_TRUE        14
    
    12           6 LOAD_FAST                0 (x)
                 9 LOAD_CONST               1 (2)
                12 BINARY_ADD          
                13 RETURN_VALUE        
           >>   14 LOAD_CONST               0 (None)
    

提交回复
热议问题