How to pass an argument through a function which call other functions?

Viewed 56

The simpler version of my problem looks like the following:

def function_1(x, function):
    print(x)
    function()


def function_2(y):
    print(2*y)


def function_3(z, n):
    print(3*z)
    print(5 * n)


function_1(5, function_2)
function_1(3, function_3)

My question is when calling function_1, how can i give it an argument which will be added to the called function (function_2 or function_3) also as an argument? Beginner here. Thanks in advance.

4 Answers

You can use functools.partial:

from functools import partial
...
function_1(5, partial(function_2, 5))
function_1(3, partial(function_3, 2, 3))

partial lets you pass a object to function_1 that can be called with no passed parameters.

As Kacper suggested, Python offers the possibility of using arbitrary positional arguments lists (args) and keyword arguments dicts (kwargs):

def fun_x(x, a_callable, *args, **kwargs):
    print(x, a_callable, args, kwargs)
    a_callable(*args, **kwargs)

def fun_y(a,b,kwarg1):
    print(a,b,kwarg1)

fun_x(3,fun_y, "first", "second", kwarg1="third")

3 <function fun_y at 0x000001D1E0E02378> ('first', 'second') {'kwarg1': 'third'}
first second third

Do you mean by adding x to the parameters?

def function_1(x, function):
    print(x)
    function(x)
...

If you want to use the same argument x to function_1 as an argument to called function inside then you can use:

def function_1(x, function): print(x) function(x)

or you want to use another argument y for function which is called inside then you can use like below:

def function_1(x,y,function): print(x) function(y)
Related