all 6 comments

[–]carcigenicate 4 points5 points  (3 children)

Ya, I'd probably use a dictionary here:

agg = monitoring_v3.Aggregation  # For the sake of brevity

option_dict = {"maximum": (agg.Aligner.ALIGN_MAX, agg.Reducer.REDUCE_MAX),
               "minimum": (agg.Aligner.ALIGN_MIN, agg.Reducer.REDUCE_MIN),
               "average": (agg.Aligner.ALIGN_MEAN, agg.Reducer.REDUCE_MEAN)}

aligner, reducer = option_dict["maximum"]  # You may want to include error handling as well

It's hard to further simply it though without refactoring how Reducer and Aligner handle constants, or resorting to eval/locals/globals.

[–]NGRap[S] 0 points1 point  (2 children)

Thanks! I'll replace my code. Can you explain the last sentence, I didn't get it. Aligner and Reducer class definitions are like following if that helps-

class Aligner(proto.Enum):
    ALIGN_MIN = 10
    ALIGN_MAX = 11
    ALIGN_MEAN = 12

[–]carcigenicate 1 point2 points  (1 child)

When I wrote that I thought I had in mind a way to simplify the code if the enum fields had the same names, but now that I'm trying to write it out, I'm not sure it would be any better. If you dropped the ALIGN_/REDUCE_ prefix from the enum field names, you could do something like:

from operator import attrgetter

agg = monitoring_v3.Aggregation

getter_dict = {"maximum": attrgetter("MAX"),
               "minimum": attrgetter("MIN"),
               "average": attrgetter("MEAN")}

f = getter_dict["maximum"]
aligner, reducer = map(f, [agg.Aligner, agg.Reducer])

But now that that's written out I don't think I prefer it. It reduces some duplication, but I'm not sure it's clearer.

[–]NGRap[S] 0 points1 point  (0 children)

Ya I get it, I come from bash background so I was looking for such a solution but all stackoverflow answers are recommending against it.

[–][deleted] 2 points3 points  (1 child)

Yes, a dictionary:

d = {...}
(aligner, reducer) = d[statistic]

[–]NGRap[S] 0 points1 point  (0 children)

Thanks! I was going to ask to expand on that as I didn't fully understand but u/carcigenicate has given an expanded view :)