mardi 6 juin 2023

Python - update the same list and dict using the output of different functions, no code repetition

I have a list and a dict, whose values I'm updating in different parts of the code using a structure like this:

final_list = []
final_dict = {}

for iter_1 in iterables_1:

    if condition_1:
        ret_1, ret_2 = function(...)
        if ret_1 is not None and ret_2 is not None:
            final_list.append(ret_1)
            final_dict[iter] = ret_2
    
    elif condition_2:
        for iter_2 in iterables_1:
            for iter_3 in iterables_3:
                ret_1, ret_2 = function(...)
                if ret_1 is not None and ret_2 is not None:
                    final_list.append(ret_1)
                    final_dict[iter] = ret_2

Now, everything works, but the lines:

ret_1, ret_2 = function(...)
if ret_1 is not None and ret_2 is not None:
    final_list.append(ret_1)
    final_dict[iter] = ret_2

are repeated (this is an oversimplification, the real code is much longer and this situation occurs more often).
In a case like this, how can I avoid this repetition?

EDIT: I forgot to mention it, one option would be to move the repeated lines to function. However, unless I'm missing something, this would require having final_list and final_dict as both arguments and return value of said function, so something like:

def function(final_list, final_dict, ...):
# calculate ret_1, ret_2
if ret_1 is not None and ret_2 is not None:
    final_list.append(ret_1)
    final_dict[iter] = ret_2

return final_list, final_dict

final_list = []
final_dict = {}

for iter_1 in iterables_1:

    if condition_1:
        final_list, final_dict = function(final_list, final_dict, ...)
    elif condition_2:
        for iter_2 in iterables_1:
            for iter_3 in iterables_3:
                final_list, final_dict = function(final_list, final_dict, ...)

But I'm not sure this is good practice either.

Aucun commentaire:

Enregistrer un commentaire