Express your intentions in your coding - short lived variables

Short Friday post. Let's talk a bit about implementation intentions and how you reflect those in your code.

The more I code, and the more I review others code, some little things start to "stress" me out a bit 😄 but it's positive stress, I've to say.

Have you considered how others read and understand the scope of your variables? More and more, I try to express my intentions when naming variables. And no, I am not talking about long names or short cryptic names. Here, I am talking about the time and the length (scope) a variable will have in the execution/implementation. Let's see. Imagine the following block of code:

var1 = # some logic

# some logic defined in 2 or 3 lines 
# using var1

# the code continues on and var1 is never used again.

Another more rigorous example could be:

var1 = # some long-line logic about 80 chars
# one shorter line using var1

# the code continues on and var1 is never used again.

How do you know that var1 is not used anywhere else in the implementation when you read these lines? You don't (until you search for it and find it's not present anywhere else). So here comes the question: How can we inform the reader that var1 is used only in the immediate scope of the following lines?

Here's what I do: prefix the variable name with _. Like this, when reading _var1, we know its scope will end in the subsequent short implementation. Of course, you can argue we could use _ only instead of _var1. That is true, and you are right. But sometimes, it is nice to name variables to give them a purpose. Also because the pure underscore _ is most often used for not used variables.

You can also use _var1 to temporarily store the result of some logic to facilitate the reading in the following lines. Here's the example I used in my previous post, where I use _tmp to simplify the next logic step.

# reduce the long call to a short temporary variable
_tmp = someobj.somemethod(run["run_dir"])
somejob = Path(
    rundir,
    f'{fileroot}_{_tmp}_{somevar}w',
    )

That's all for this Friday short post. Let me know your comments,
Cheers,

25