Python - ternary operator or if statement? Which of these two alternatives is more readable?

token = map.get(token_str)
if not token:
   token = Course(token_str)
return token


or

token = map.get(token_str)
token if token else Course(token_str)
get() takes an optional second parameter, for a value to use if the key isn't present:

token = map.get(token_str, Course(token_str))


I think that one is clearly the best solution, unless you don't want to create and immediately throw away a Course object. In that case, I would use 'or':

token = map.get(token_str) or Course(token_str)


Both of these are only one line, that one line is quite readable, and there is no unnecessary repetition.

There is one third possible situation, in which you don't want to unnecessarily construct a Course instance, and you also can't rely on the values that are present to evaluate as True. Then 'or' wouldn't work correctly.

Then I would use an 'if' statement:

token = map.get(token_str)
if token is None:
    token = Course(token_str)


but that's personal preference. Something using 'in' is also fine:

token = map[token_str] if token_str in map else Course(token_str)


although of course that looks up token_str in map twice, so if you need to be really time efficient then don't do that.