Philipp
Philipp

Reputation: 79

How can I define the argument name of an inner function in an outer function?

I have a function f_1 with different default input arguments, e.g. arg_1 and arg_2. Now I want to call f_1 with another function f_2 and change one of the default arguments, let us say arg_1. How can I tell f_2 that I want to change arg_1 in f_1?

def f_1(arg_1 = x, arg_2 = y):
    some computations
    return result

def f_2(value_for_arg_f_1, name_arg_f_1):
    do some stuff
    out_f_1 = f_1(name_arg_f_1 = value_for_arg_f_1)
    do some more stuff
    return result_f_2
end_result = f_2(z, arg_2)

So looking in the example code - what do I have to write for name_arg_f_1 in f_2, such that (in the computation of end_result) out_f_1 = f_1(arg_2=z)?

Upvotes: 0

Views: 49

Answers (2)

CristiFati
CristiFati

Reputation: 41116

You could use the example from [Python 3.Docs]: Glossary - argument:

complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})

It relies on [Python]: PEP 448 - Additional Unpacking Generalizations.

>>> def f1(arg1=1, arg2=2):
...     print("    Argument 1: [{:}], Argument 2: [{:}]".format(arg1, arg2))
...
>>>
>>> f1()
    Argument 1: [1], Argument 2: [2]
>>>
>>> def f2(f1_arg_val, f1_arg_name):
...     f1(**{f1_arg_name: f1_arg_val})
...
>>>
>>> f2("value for argument 2", "arg2")
    Argument 1: [1], Argument 2: [value for argument 2]

Upvotes: 1

Andrew Allen
Andrew Allen

Reputation: 8002

You can use lambda functions, for example,

def adder(x=2, y=3):
    return x+y

adder()
# 5

adderEight = lambda y: adder(8, y)
adderEight(10)
# 18

Upvotes: 0

Related Questions