How to set variable to key of keyword arguments of function?

question

#1

hi, everyone~
my code like this:

function hello(;name="world")
     println("hello, $(name)")
end

keyname = "name"
hello(keyname="today") # I don't want to use hello(name="today") directly~

then will get error:
ERROR: LoadError: MethodError: no method matching hello(; keyname=“today”)
Closest candidates are:
hello(; name) at /ifshk7/BC_PS/sikaiwei/software/julia/tmp.jl:3 got unsupported keyword argument “keyname”
Stacktrace:

I am using julia1.0.2~
Thanks~

Regards
Si


#2

That’s an usual question. It would help to know why you don’t want to use hello(name="today") directly. Keyword arguments (like name in hello(;name) are intended to be set by assigning to the keyword when the function is called (hello(name="today")). There is no language-level provision for dynamically changing the keyword. Not knowing the purpose makes it difficult to advise … you might do this:

function hello(;name::String)
    println(string("hello ",name))
end

hello2(;keyname::String) = hello(name = keyname)

hello2(keyname="world")
# prints: hello world

#3

Eg, among other solutions,

hello(;name="world") = println("hello, $(name)")
keyname = "name"
hello(; Dict( Symbol(keyname) => "today")...) # with a Dict
hello(; NamedTuple{(Symbol(keyname), )}(("today", ))...) # with a NamedTuple

but I concur with @JeffreySarnoff, this is not necessarily idiomatic and will definitely result in a (minor) performance penalty.

Perhaps provide more context about your problem.


#4

@JeffreySarnoff @Tamas_Papp thanks~ Originly I want to write a CLI package(like fire package of python https://github.com/google/python-fire), then I guess maybe I should pass ARGS as keyword arguemnt of function which is fired.


#5

thanks! The last line code with NamedTuple works ~

hello(; NamedTuple{(Symbol(keyname), )}(("today", ))...) # with a NamedTuple

#6

Why not just

hello(; Symbol(keyname) => "today")

?


#7

thanks a lot, the code works and is more cleaner ! I am a fresh bird of julia, give me some time to really understand this syntax.


#8

@JeffreySarnoff @Tamas_Papp @tkoolen thanks for the kind help! I just wrote my first julia package in github( https://github.com/orangeSi/Jfire.jl), it only support call Function from Module or Function directly yet, it is simple that need to go ahead~