I have a function that treats and returns data, but according to a boolean input parameter, should do a slightly different treatment (not different enough to justify a new function, I think). This slightly different treatment also requires the returning of an additional parameter.
Let’s say I have this.
def func(data, special_case = False):
#Do treatment
...
if special_case:
#do some more stuff
...
#return results
if special_case:
return results, extra_results
else:
return results
Is that considered clean? Or maybe I should always return the second variable, but just make it empty when I’m not treating the special case?
#return results
if special_case:
extra_results = something
else:
extra_results = []
return results, extra_results
No, I don’t think so. Now your caller has to know about your function internals, specifically that your option changes the return type. That’s just another thing for the caller to remember, and is poor encapsulation.
I would either split this into two functions (preferred), or return a
Noneplaceholder, or return an object that can be introspected for additional elements. But the structure of the returned data type should not change.