I've built a function that tries to extract some information from a string.
Before: function (string)
Now, I want to refactor that function by receiving two extra params, call them param_1, param_2.
Now: function(string, param_1:str, param_2:str)
The function is imported to the namespace where the string and parameters reside, and I can only know the exact values of param_1, param_2 at runtime, even though they belong to a long list, which is known in advance.
However, I was thinking that instead of just doing function (string, param_1, param_2)
, and then branching out with a lot of elif
statements
if param_1 == val_11 and param_2 == val_12:
<some_code>
elif param_1 == val_21 and param_2 == val_22:
<some_different_code>
elif (...)
I could just do something like:
def function(string, param_1:str, param_2:str):
new_function = eval(param_1_param_2_<old_function_name>)
return new_function(string)
And then define separately each param_1_param_2_<old_function_name>
.
- Is there a more pythonic way of solving my original problem?
- From a software engineering perspective / clean code, should I do something else instead?
Edit: The objective is to extract information from the string. Let's assume the info is dates in a document. Depending on the document type (param_2), and on the author (param_1), the way a date is formatted will differ. The focus of the question is not on better machine learning models, or functions like dateparser (but if you do have a suggestion, leave a comment :) ), but how to 'branch out' the original function.
extract_dates(string, author, doc_type)