In C# I could easily write the following:
string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
Is there a qu
It's never a bad thing to write readable, expressive code.
if otherString:
stringValue = otherString
else:
stringValue = defaultString
This type of code is longer and more expressive, but also more readable and less likely to get tripped over or mis-edited down the road. Don't be afraid to write expressively - readable code should be a goal, not a byproduct.
If you used ruby, you could write
stringValue = otherString.blank? ? defaultString : otherString;
the built in blank?
method means null or empty.
Come over to the dark side...
You can take advantage of the fact that logical expressions return their value, and not just true or false status. For example, you can always use:
result = question and firstanswer or secondanswer
With the caveat that it doesn't work like the ternary operator if firstanswer is false. This is because question is evaluated first, assuming it's true firstanswer is returned unless firstanswer is false, so this usage fails to act like the ternary operator. If you know the values, however, there is usually no problem. An example would be:
result = choice == 7 and "Seven" or "Another Choice"
I also discovered that just using the "or" operator does pretty well. For instance:
finalString = get_override() or defaultString
If get_override() returns "" or None, it will always use defaultString.
Chapter 4 of diveintopython.net has the answer. It's called the and-or trick in Python.
In Python 2.5, there is
A if C else B
which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:
stringValue = otherString or defaultString