Conditional operator in Python?

thp at cs.ucr.edu thp at cs.ucr.edu
Tue Sep 4 19:56:04 EDT 2001


Donn Cave <donn at u.washington.edu> wrote:
: Quoth thp at cs.ucr.edu:

: | I don't see why, say
: |
: |    if by_land():
: |      lantern_count = 1
: |    elif by_sea():
: |      lantern_count = 2
: |    else: 
: |      lantern_count = 0
: |
: | should be more readable than, say
: |
: |    lantern_count = 
: |      if    by_land() :  1 
: |      elif  by_sea()  :  2 
: |      else            :  0
: |
: | or simply
: |
: |    lantern_count = if by_land(): 1 elif by_sea(): 2 else: 0


: No, next you'll want
:
: lantern_count = if by_land(): (
:      if by_bicycle(): 1 elif by_automobile(): 4 elif by_foot(): 5
:    ) elif by_sea(): 2 else: 0

Such prescience should include correct syntax and reasonable
formatting, e.g.:

  lantern_count = 
    if by_land(): 
      if   by_bicycle()    : 1 
      elif by_automobile() : 4 
      elif by_foot()       : 5
      else                 : 6
    elif by_sea(): 
      2 
    else: 
      0

: Now replace "0", "1" etc. with non-trivial computations.

Pick your favorite experssions, possibly including function calls.

: | Lambda abstraction is a powerful feature that needs to be supported
: | with a selection operator.  The ?: notation is not the only option
: | for such a ternary operator.

: Sure you can't just "def" an ordinary function with a name?

A short-circuiting selection operator cannot be defined as an ordinary
function, since there is no way to selectively short-circuit the
evaluation of arguments.

Tom Payne















More information about the Python-list mailing list