Assume I'm calling a function fu()
inside another function f2()
. I would like to pass to fu()
some of the optional arguments. Is it possible?
def f0( arg1, arg2 = None):
print( arg1 )
if arg2 is not None:
print( f'arg2 of f0() is: {arg2}' )
def f1( arg1, arg2 = None, arg3 = None ):
print( arg1 )
if arg2 is not None:
print( f'arg2 of f1() is: {arg2}' )
if arg3 is not None:
print( f'arg3 of f1() is: {arg3}' )
def f2( fu, arg1, *args, **kwargs ):
fu( arg1, ??? )
I'm wondering if it is possible to write the code above in a way that something like this would work:
f2(f0, 1)
> 1
f2(f0, 1, 2)
> 1
> arg2 of f0() is: 2
f2(f0, 1, 2, 3)
> Error
f2(f1, 1)
> 1
f2(f1, 1, 2)
> 1
> arg2 of f1() is: 2
f2(f1, 1, 2, 3)
> 1
> arg2 of f1() is: 2
> arg3 of f1() is: 3
???
> 1
> arg3 of f1() is: 2
If a solution does not exist, maybe something similar could be achieved by using dictionaries?
UPDATE
The question above was answered by @keanu in the comment to this question. Here is an extended version.
Now I would like to pass two functions to f2()
, as well as optional parameters to those. My idea was to somehow use dictionaries:
def f2( fu0, fu1, arg10, arg11, f0_args = None, f1_args = None ):
fu0( arg10, f0_args )
fu1( arg11, f1_args )
This, however, does not work:
f2( f0, f1, 1, 2, f1_args = { 'arg3' : 4 } )
> 1
> 2
> arg2 of f1() is: {'arg3': 4}
While I would like to get
> 1
> 2
> arg3 of f1() is: 4
Is there a way to do this?
YAAAAAY, SEEMS TO BE WORKING:
def f2( fu0, fu1, arg10, arg11, f0_args = None, f1_args = None ):
if f0_args is None:
fu0( arg10 )
else:
fu0( arg10, **f0_args )
if f1_args is None:
fu1( arg11 )
else:
fu1( arg11, **f1_args )
Not too elegant though...