mcp
mcp

Reputation: 23

Passing variables and a function (with different arguments) to a function

I have an external function external_function which takes as arguments x, y, step and another function func which takes as arguments x, y and (in general, but not always) other variables. I don't know how to pass these additional arguments.

I've tried with *args or with functools.partial, but it didn't work. Maybe, I didn't use them in the right way.

This is an example that represents the problem of my real code:

def general_operation(x, y, step, func):
    """
    func is a function which expects at least x & y as arguments,
    but it can expect more arguments.
    """
    number_of_iterations = int((y - x) / step)
    solutions = []
    for i in range(number_of_iterations):
        solutions.append(func(x, y))
    return solutions

def funza(x, y):
    return x + y

def gunza(x, y, additional):
    if additional == 0:
        return x + y
    elif additional == 1:
        return x - y
    elif additional == 2:
        return x * y
    elif additional == 3:
        return x / y

x = 0
y = 100

step = 0.01

# works
solutions_1 = general_operation(x, y, step, funza)

# do not know how to pass "additional" argument here
solutions_2 = general_operation(x, y, gunza)

# do not know how to pass "additional" argument here
solutions_3 = general_operation(x, y, step, gunza)

print(solutions_1)
print(solutions_2)
print(solutions_3)

Upvotes: 0

Views: 48

Answers (1)

tituszban
tituszban

Reputation: 5152

You can use *args and **kwargs:

def general_operation(x, y, step, func, *args, **kwargs):
    """
    A function which expects at least x & y as arguments,
    but it can expect more arguments.
    """
    number_of_iterations = int((y - x) / step)
    solutions = []
    for i in range(number_of_iterations):
        solutions.append(func(x, y, *args, **kwargs))
    return solutions

Here *args will contain all unnamed arguments in a tuple and **kwargs will contain all named arguments in a dictionary.

You would invoke it like this:

solutions_1 = general_operation(x, y, step, funza)

solutions_2 = general_operation(x, y, step, gunza, 1)

All additional arguments beyond func will be passed along to func

Upvotes: 1

Related Questions