问题
At times I have a variable that I want to default to something and if something else is set change it to something else.
The question is. What is preferred? Setting the default value and then changing it if the condition is met or setting the condition only once depending on the initial check with an added else?
Example in code.
if x:
y = '%s-other' % x
else:
y = 'some_default'
The other option would be.
y = 'some_default'
if x:
y = '%s-other' % x
This isn't always an argument passed in to a function so kwargs is not something I want to rely on here.
Personally, the second one seems to be a lot more clear to me but what I have yet to find any sort of opinion by anyone on this.
回答1:
How about this:
y = '%s-other' % x if x else 'some_default'
回答2:
As Rob pointed out,
y = '%s-other' % x if x else 'some_default'
is a very common construct across various language
Python provides some more alternatives and the choice depends on the User
y = ['some_default','%s-other'][x!=None]
If you are dealing with dictionary, it already has two options
- Use setdefault like
x.setdefault(some_key,some_default)=other
- Use collections.defaultdict
The other's you posted are also valid but not very pythonic but yet you will encounter lot of code with your quoted style.
To me, as long as a program is readable, efficient, we should not be too bogged down to make some contruct pythonic which often deviates the focus.
回答3:
More sugar to other answers:
y = x and '%s-other' % x or 'some_default'
But this one may scare people so I'd recomend to use Rob's one :)
来源:https://stackoverflow.com/questions/8732867/python-default-values-and-setting-the-value-based-on-other-variables-to-if-else