I've defined a bunch of custom functions and find a lot of them include some identical or similar blocks of code (e.g. just including slightly different strings or arguments). So something like:
def func1(a, b, c):
some_identical_code
some_similar_code
more_identical_code
some_unique_code
final_similar_code
# similarly for func2, func3...
I would like to try to combine these into a single function that takes an additional 'setting' argument, both because the functions are obviously related and to make the code more compact. The obvious but inelegant flow for this would be something like:
def func(a, b, c, setting):
# setting = '1', '2', etc.
some identical code
if setting == '1':
similar_code_1
elif setting == '2':
similar_code_2
# etc. for other settings options
more_identical_code
if setting == '1':
unique_code_1
final_similar_code_1
elif setting == '2':
unique_code_2
final_similar_code_2
# etc. for other settings options
How can I do something like this more elegantly? Is there a standard way to do it?
One option I'm trying is to use dictionaries built into the function to parse the similar code blocks:
def func(a, b, c, setting):
# setting = '1', '2', etc.
simdict = {'1': '_1', '2': '_2' ...}
some identical code
similar_code(simdict[setting])
more_identical_code
if setting == '1':
unique_code_1
elif setting == '2':
unique_code_2
# etc. for other settings options
final_similar_code(simdict[setting])
This helps but 1) I'm not sure if it's good design and 2) it only helps so much when the identical vs. similar vs. unique code is very interspersed.
some_identical_code,more_identical_codeandfinal_similar_codeinto separate functions (maybe with parameters as in the third case) and call them fromfunc1,func2etc.