0

In my current project, I have a function which calls a second, nested function. This nested function has one obligatory input (x), but can demand a number of other arguments as well (say: y, z). Without changing the structure of the outer function, is there a way to pass the optional arguments to the inner/nested function? Imagine, for example, something like this:

# Define the outer function
def outer_function(x,args):

    # This function calls a nested function
    def inner_function(x,y,z):
        return x*y + z

    return inner_function(x,args) 

# The following does NOT work
result = outer_function(x = 1, args = (2,3))

The SciPy optimizers, for example, have a similar capability, where you only require x as a primary input and can pass any secondary inputs as a tuple through the 'args' variable to the inner function we seek to optimize.

Do you know how I can implement this? Note that I do not want to unpack the 'args' variable in the outer function. If at all possible, I would like to pass these arguments directly on to the inner function.

J.Galt
  • 529
  • 3
  • 15
  • 5
    `return inner_function(x, *args)` works, but you say you don't want unpacking. Is there a reason for that? – Carcigenicate Jan 23 '21 at 23:33
  • then have one parameter in the inner function, `args` and declare `x = args[0]; y = args[1]; z = args[2]` or `x, y, z = args` if `args` is of length `3`. – Countour-Integral Jan 23 '21 at 23:36
  • @Carcigenicate: No, perfect, this does it! I didnt know unpacking like this was possible. What I wanted to avoid was adding new lines to the outer function to unpack args manually, but this does the trick beautifully! – J.Galt Jan 23 '21 at 23:57
  • @Carcigenicate Wanna make that an answer? – Cyphase Jan 24 '21 at 00:30
  • 1
    Does this answer your question? [Pass a list to a function to act as multiple arguments](https://stackoverflow.com/questions/3480184/unpack-a-list-in-python) – Carcigenicate Jan 24 '21 at 01:04
  • Even better, I found a dupe. – Carcigenicate Jan 24 '21 at 01:04

0 Answers0