Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use elif if I have already returned from the function in a previous block?

def size(number):
    if number<100:
        return Small()

    if number<1000:
        return Medium()

    return Big()

def size1(number):
    if number<100:
        return Small()
    elif number<1000:
        return Medium()
    else:
        return Big()

Regarding coding style: I often use the former when the following blocks, or the last block is a large chunk of code. It seems to help readability.

I generally use the latter when the various blocks have a common concept running through them (as in the case above). The common indentation helps to communicate their relationship.

Are there any differences between these two worth noting (esp. performance wise)?

like image 291
cammil Avatar asked May 15 '12 10:05

cammil


1 Answers

Style-wise, I find the second example easier on the eye.

In all other respects, there is no difference. The two functions compile to identical bytecodes:

In [3]: dis.dis(size)
  2           0 LOAD_FAST                0 (number)
              3 LOAD_CONST               1 (100)
              6 COMPARE_OP               0 (<)
              9 POP_JUMP_IF_FALSE       19

  3          12 LOAD_GLOBAL              0 (Small)
             15 CALL_FUNCTION            0
             18 RETURN_VALUE        

  5     >>   19 LOAD_FAST                0 (number)
             22 LOAD_CONST               2 (1000)
             25 COMPARE_OP               0 (<)
             28 POP_JUMP_IF_FALSE       38

  6          31 LOAD_GLOBAL              1 (Medium)
             34 CALL_FUNCTION            0
             37 RETURN_VALUE        

  8     >>   38 LOAD_GLOBAL              2 (Big)
             41 CALL_FUNCTION            0
             44 RETURN_VALUE        

In [4]: dis.dis(size1)
 11           0 LOAD_FAST                0 (number)
              3 LOAD_CONST               1 (100)
              6 COMPARE_OP               0 (<)
              9 POP_JUMP_IF_FALSE       19

 12          12 LOAD_GLOBAL              0 (Small)
             15 CALL_FUNCTION            0
             18 RETURN_VALUE        

 13     >>   19 LOAD_FAST                0 (number)
             22 LOAD_CONST               2 (1000)
             25 COMPARE_OP               0 (<)
             28 POP_JUMP_IF_FALSE       38

 14          31 LOAD_GLOBAL              1 (Medium)
             34 CALL_FUNCTION            0
             37 RETURN_VALUE        

 16     >>   38 LOAD_GLOBAL              2 (Big)
             41 CALL_FUNCTION            0
             44 RETURN_VALUE        
             45 LOAD_CONST               0 (None)
             48 RETURN_VALUE        

(To be 100% accurate, the second version has an implicit return None at the end. However, since this code is not reachable, it won't affect performance.)

like image 109
NPE Avatar answered Jan 02 '23 11:01

NPE