Reputation: 85
So I am trying to make a case statement for my python script to make it cleaner but there's no such thing (as far as I'm aware) so I have just made a bunch of if/else statements. Is there any way to make this cleaner?
if (config.dutCardTypes[0] in [6, 7]) and (config.isPrimary) and (config.measPwr): ### Power Measurement for 28nm on Primary Only
if dsppif[dutDevId].pifReadData(0x1e800) == 0x1 :
print "Link Up, Measuring SteadyState Power..."
if (("Sahara Validation" in dsppif[dutDevId].board.description)) :
v, i, pwr = getOnBoardPwr(dsppif[dutDevId],"Sahara Validation")
vdd21A_pwr = pwr["P2V1"]
vdd12A_pwr = pwr["P1V2"]
vdd_pwr = pwr["VDD"]
vdd3v3_pwr = pwr["P3V3"]
elif "Athena" in dsppif[dutDevId].board.description:
if (("Quad A" in dsppif[dutDevId].board.description)) :
v, i, pwr = getOnBoardPwr(dsppif[dutDevId],"Athena Quad A")
vdd21A_pwr = pwr["P2V1_A"] + pwr["P2V1_B"] + pwr["P2V1_C"] + pwr["P2V1_D"] + pwr["P2V1_E"]
vdd12A_pwr = pwr["P1V2_A"] + pwr["P1V2_B"]
vdd_pwr = pwr["VDD"]
elif (("Quad B" in dsppif[dutDevId].board.description)) :
v, i, pwr = getOnBoardPwr(dsppif[dutDevId],"Athena Quad B")
vdd21A_pwr = pwr["P2V1_A"] + pwr["P2V1_B"] + pwr["P2V1_C"] + pwr["P2V1_D"] + pwr["P2V1_E"]
vdd12A_pwr = pwr["P1V2_A"] + pwr["P1V2_B"]
vdd_pwr = pwr["VDD"]
elif (("Quad C" in dsppif[dutDevId].board.description)) :
v, i, pwr = getOnBoardPwr(dsppif[dutDevId],"Athena Quad C")
vdd21A_pwr = pwr["P2V1_A"] + pwr["P2V1_E"]
vdd12A_pwr = pwr["P1V2_A"]
vdd_pwr = pwr["VDD"]
Upvotes: 1
Views: 8684
Reputation: 2888
At a high level, python suggests that you try and use dictionaries for this kind of thing. I won't try and translate your example, since it's a little verbose, but essentially instead of using a case statement like so:
function(argument){
switch(argument) {
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
default:
return "nothing";
};
};
You can use a dictionary of possibilities like so
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(argument, "nothing")
You could also create a switcher class, and map your actions to your conditions. Overall the python way is to increase legibility.
Upvotes: 3