Calling julia functions with keyword arguments using macro

I’m trying to write a macro which calls functions with keyword arguments (for using in JuMP NLexpressions and mappings. This functions are just functions for accessing a database. So they do not represent a mathematical operation).

Minimal example:

function foo1(; int::a=1)
    a
end

function foo2(; int::a=1, int::b=2)
    b
end

macro callfunc(f, keywordargs)
    #function should be called here using symbol
    #return values of f should be returned by macro callfunc
    ex= :($(that)(;$(keywordargs)...)) #this syntax is not correct for sure
    return eval(ex) 
end

@callfunc(foo1, (a=1))
#should return 1

@callfunc(foo2, (a=1, b=2))
#should return 2

I hope you get my idea, I really appreciate your help!

You don’t really need a macro for that:

julia> f(;a::Int=1) = a
f (generic function with 1 method)

julia> g(;a::Int=1, b::Int=2) = b
g (generic function with 1 method)

julia> f(;(a=1,)...)
1

julia> g(;(a=1, b=22)...)
22

although you could define a wrapper function that makes the syntax slightly nicer:

julia> wrap(f, x::NamedTuple) = f(;x...)
wrap (generic function with 1 method)

julia> wrap(g, (a=1,b=44))
44
1 Like