Increment variable without initializing

Question:

I’m extracting a bunch of features from a protein (using a scientific software called UCSF Chimera, which only works with Python 2.7).

I have a function that returns a NamedTuple with the results from a ton of counters–around 35 of them (where each counter represents some sort of sum of features).

At first, I wrote something like this:

var1, var2, var3, ... var35 = (0, ) * 35

for my_object in my_objects:
     var1 += my_object.getVar1()
     # etc
     return MyFeatures(var1 = var1, var2 = var2, ...)

This looks pretty messy, in part because var1, var2, .... = (0, ) * 35 takes up quite a few lines.

I’m thinking about rewriting the code like this:

for my_object in my_objects:
    var1 = var1+my_object.getVar1() if 'var1' in vars() else my_object.getVar1()
    # etc
    return MyFeatures(var1 = var1, var2 = var2, ...)

But repeating that 35 times might be even worse than the initialization block in the previous version.

Do you have any suggestions? Is there some sort of best practice for initializing a large group of counters–is there a pythonic way to increment a variable that isn’t yet initialized?

Asked By: julianstanley

||

Answers:

You can put all your counters in a dict, and initialize them with the dict.fromkeys method:

var_names = ["aaind_molecular_volume_sum", "oh_rxn_constant_sum"]
counters = dict.fromkeys(var_names, 0)
print(counters)
# {'aaind_molecular_volume_sum': 0, 'oh_rxn_constant_sum': 0}

counters["oh_rxn_constant_sum"] += 1
print(counters)
# {'aaind_molecular_volume_sum': 0, 'oh_rxn_constant_sum': 1}
Answered By: Thierry Lathuille
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.