I’ve recently found myself using the following pattern a lot:
x = 3
if this:
this.process()
if this.something:
x = this.a_value
I don’t want to do this:
if this and (this.process() or True) and this.someting:
x = this.a_value
else:
x = 3
or this:
if this:
this.process()
if this.something:
x = this.a_value
else:
x = 3
else:
x = 3
but I can’t help but feel that setting the value and then changing it is a little messy, especially considering in some use cases the fallback value is seldom used.
Is there a better/tidier way?
I think of the three options you present, the first one, i.e., the one you are using, is the best. The code is clear and everyone will know what’s happening. I can’t think of a neater/tidier way, this is how I would code it too, based on the “Simple is better than complex.” principle
Re “I can’t help but feel that setting the value and then changing it is a little messy,” if you want a default value, there’s no way around setting one.
It certainly is much tidier than using the other two
elseapproaches. Readability counts.