[SOLVED] How can you create a function with variable return values Python?

Issue

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

I would make your function more general. Rather than take a boolean argument that decides whether or not to append to a list, take an arbitrary function to be called on each solution.

def function(initial_sol, tolerance, f=None):
    solution = initial_sol
    difference = 1
    while difference > tolerance
        newsolution = step_func(solution)
        difference = diff_func(newsolution, solution)
        if f is not None:
            f(newsolution)

        solution = newsolution

    return solution

Then you can call

s = function(x, t)

or

extra_data = []
s = function(x, lambda x: extra_data.append(extrafunction(x)))

Though repeatedly checking if f is not None is probably cheaper than unconditionally calling a trivial function, you could also write

def function(initial_sol, tolerance, f=lambda x: x):
    solution = initial_sol
    difference = 1
    while difference > tolerance
        newsolution = step_func(solution)
        difference = diff_func(newsolution, solution)
        f(newsolution)

        solution = newsolution

    return solution

as calling the identity function on newsolution is just a relatively expensive no-op.

Answered By – chepner

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.