Python default values and setting the value based on other variables. To if else or to not.

人盡茶涼 提交于 2020-01-14 10:26:11

问题


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

  1. Use setdefault like x.setdefault(some_key,some_default)=other
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!