Home > Net >  Use nested if or and [closed]
Use nested if or and [closed]

Time:09-24

Is one of these considered better practice?

a, b, c = True, int(), 'Hello World!'

if a:
    if isinstance(b, int):
        if c == 'Hello World!':
            pass
a, b, c = True, int(), 'Hello World!'

if (
    a
    and isinstance(b, int)
    and c == 'Hello World!'
):
    pass

Provided that there will be no else statements

CodePudding user response:

Performance-wise, they both generate the same bytecode:

import dis

a, b = 1, 2

def nested():
    if a:
        if b:
            pass

def _and():
    if a and b:
        pass

dis.dis(nested)
print('***********************************')
dis.dis(_and)

outputs

 6           0 LOAD_GLOBAL              0 (a)
              2 POP_JUMP_IF_FALSE        8

  7           4 LOAD_GLOBAL              1 (b)
              6 POP_JUMP_IF_FALSE        8

  8     >>    8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
***********************************
 11           0 LOAD_GLOBAL              0 (a)
              2 POP_JUMP_IF_FALSE        8
              4 LOAD_GLOBAL              1 (b)
              6 POP_JUMP_IF_FALSE        8

 12     >>    8 LOAD_CONST               0 (None)
             10 RETURN_VALUE

Visually, using and has the advantage of using only one indentation level, especially if written as a single line (even black prefers that):

if a and isinstance(b, int) and c == "Hello World!":

If you have too many conditions to fit on a single line, just move the check to a function:

def should_do_it():
    return a and isinstance(b, int) and c == "Hello World!"

if should_do_it():
    pass
  • Related