Skip to content

Comment on Python does support if-else in lambdas...parent

Comments

The problem with that construct is that trueaction itself must evaluate to true, or the expression will evaluate to falseaction, which most likely is not what you want:

  >>> 0 if 1 else 2
  0
  >>> 1 and 0 or 2
  2
Even crazier things can happen if trueaction has side effects:
  >>> def trueaction():
  ...     print 'trueaction called'
  ...     return 0
  ...
  >>> def falseaction():
  ...     print 'falseaction called'
  ...     return 'hello'
  ...
  >>> True and trueaction() or falseaction()
  trueaction called
  falseaction called
  'hello'
  >>> trueaction() if True else falseaction()
  trueaction called
  0
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.