'How can you create a function with variable return values Python?
I am writing a function in Python and cannot figure out the best way to implement an argument that allows the user to choose whether or not to compute an extra bit of data. It looks roughly like this
def function(initial_sol, tolerance, compute_extra_data = False) :
solution = initial_sol
difference = 1
extra_data = []
while difference > tolerance :
newsolution = step_func(solution)
difference = diff_func(newsolution, solution)
if compute_extra_data :
extra_data.append(extra_function(newsolution))
solution = newsolution
return solution, extra_data
As extra_function in my actual code is a more expensive operation and gives extra information the user might not necessarily want, I wanted it to be optional. However, I'm not really sure if this is a good way of implementing that. Also I'd quite like to make it so that if compute_extra_data = False, the return value will just be the solution object, rather than a tuple with both items.
I appreciate and suggestions/ideas, thanks!
Solution 1:[1]
How about wrapping the the output in a dictionary?
...
out ={'solution': solution }
if compute_extra_data:
out['extra_data']: extra_data
return out
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Micha336 |
