Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 742
ScottZ Avatar asked Jan 17 '23 21:01

ScottZ


1 Answers

How about this:

y = '%s-other' % x if x else 'some_default'
like image 166
Rob Wouters Avatar answered May 14 '23 08:05

Rob Wouters