The ternaery operator
William Mayor
mail at williammayor.co.uk
Thu Mar 16 11:11:49 EDT 2017
>
> I think it would be nice to have a way of getting the 'true'
> value as the return with an optional value if false. The desire
> comes about when the thing I'm comparing is an element of a collection:
>
> drugs['choice'] if drugs['choice'] else 'pot'
>
> Then I'm tempted to do:
>
> chosen = drugs['choice']
> chosen if chosen else 'pot'
>
> I sometimes feel like doing:
>
> drugs['choice'] else 'pot'
>
For the case where the element in the collection exists, but might be falsey you could do:
drugs[‘choice’] or ‘pot'
The ternary operator would be useful for something like:
drugs[‘choice’] if is_good_for_you(drugs[‘choice’]) else ‘nice cup of tea’
Most of the time I avoid the ternary stuff though, I don’t think it’s easy to read, no matter what language you’re writing in.
More information about the Python-list
mailing list