Passing keyword arguments from a function to the other

I need to replicate the following python code, where f1 is called with a function name, a positional argument and some keyword ones, and it passes to the function defined in its first argument the positional argument and the keyword arguments:

Python code:

def f1(fname,val,**kwargs):
    return fname(val,**kwargs)
def f2(val, kw1, kw2):
    return (val+1+kw1)/kw2
def f3(val, kw3):
    return (val+1+kw3)
f1(f2,5,kw1=4,kw2=2)
f1(f3,5,kw3=4)

This is what I have tried up to now, but I still have a method error:

Julia code:

function f2(val, kw1, kw2)
    return (val+1+kw1)/kw2
end
f2(val; kw1, kw2) = f2(val, kw1, kw2)
function f3(val, kw3)
    return (val+1+kw3) 
end
f3(val; kw3) = f3(val, kw3)
function f1(fname,val;kwargs...)
    return fname(val,collect(kwargs)...)
end
f1(f3,2,kw3=3)
function f1(fname, val; kwargs...)
    return fname(val; kwargs...)
end

?

1 Like

Hi,
the method error says that there is: no method matching +(::Int64, ::Pair{Symbol,Int64}). As your keyword kw3 is stored as a Pair. You probably want to access its second field: kw3.second

So the whole code might look like:

function f2(val, kw1, kw2)
    return (val+1+kw1)/kw2
end
f2(val; kw1, kw2) = f2(val, kw1, kw2)
function f3(val, kw3)
    return (val+1+kw3.second)
end
f3(val; kw3) = f3(val, kw3)
function f1(fname,val;kwargs...)
    return fname(val,collect(kwargs)...)
end
f1(f3,2,kw3=3)

Thank you. I wasn’t aware in using ; in calling a function.