I have three similarmethods. And I think this can be reduced to one method.
So I have this almost identical methods:
def calulate_totalAnanas_NorthMidSouth():
sheet_factuur = excelWorkbook['Facturen ']
totalAnanasNorth = sheet_factuur.cell(row=6, column=5).value
totalAnanasMid = sheet_factuur.cell(row=7, column=5).value
totalAnanasSouth = sheet_factuur.cell(row=8, column=5).value
totalAnanasNoMidSou = totalAnanasNorth + totalAnanasMid + totalAnanasSouth
print(totalAnanasNoMidSou)
def calulate_totalApples_NorthMidSouth():
sheet_factuur = excelWorkbook['Facturen ']
totalAppleNorth = sheet_factuur.cell(row=9, column=5).value
totalApplesMid = sheet_factuur.cell(row=10, column=5).value
totalAppleSouth = sheet_factuur.cell(row=11, column=5).value
totalAppleNoMidSou = totalAppleNorth + totalApplesMid + totalAppleSouth
print(totalAppleNoMidSou)
def calulate_totalWaspeen_NorthMidSouth():
sheet_factuur = excelWorkbook['Facturen ']
totalWaspeenNorth = sheet_factuur.cell(row=12, column=5).value
totalWaspeenMid = sheet_factuur.cell(row=13, column=5).value
totalWaspeenSouth = sheet_factuur.cell(row=14, column=5).value
totalWaspeenNoMidSou = totalWaspeenNorth + totalWaspeenMid + totalWaspeenSouth
print(totalWaspeenNoMidSou)
So my question is:how to refactor this?
try this code. Note that i have not tested it but idea is clear:
def calulate_total_fruit_NorthMidSouth(fruit_name: str) -> int:
sheet_factuur = excelWorkbook['Facturen ']
fruit_name_rows = {
'ananas': [6, 7, 8],
'apple': [9, 10, 11],
'waspeen': [12, 13, 14],
}
total_fruit_counts = [sheet_factuur.cell(
row=row_num, column=5).value for row_num in fruit_name_rows.get(fruit_name)]
return sum(total_fruit_counts)
print(calulate_total_fruit_NorthMidSouth('ananas'))
print(calulate_total_fruit_NorthMidSouth('apple'))
print(calulate_total_fruit_NorthMidSouth('waspeen'))
Note!: you should pass rows as parameters to eliminate hardcoding.