I'm quite acquainted with Python's ternary operator approach:
value = foo if something else bar
My question is very simple: without prior assignments, is there anyway to reference the term being evaluated in (if ...
) from one of the return operands (... if
or else ...
)?
The motivation here is that sometimes I use expressions in if ...
that are exactly what I'd like to have as result in the ternary operation; happens though that, for small expressions, there's no problem repeating it, but for a bit longer expressions, it goes somewhat nasty. Take this as an example:
value = info.findNext("b") if info.findNext("b") else "Oompa Loompa"
findNext
take an optional default value, likeget
and the hundreds of other methods modeled after it? Then you don't need this at all. – CapsularfindNext
is not a function I wrote; this is fromBeautifulSoup
parser API. – While