Code formatting question: conditional expression

John Posner jjposner at optimum.net
Tue Aug 18 10:04:36 EDT 2009


While refactoring some code, I ran across an opportunity to use a 
conditional expression. Original:

  if total > P.BASE:
      excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True)
  else:
      excessblk = None

Is there any consensus on how to format a conditional expression that is 
too long for one line? How about this:

  excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True)
               if total > P.BASE else
               None)

The above format separates the values from the if-then-else machinery. 
Too many lines? Would it be better to line up "if" and "else" 
vertically? ...

  excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True)
               if total > P.BASE
               else None)

PEP 308 is silent on this topic.

-John




More information about the Python-list mailing list