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

hi, everyone~
my code like this:

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

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”

I am using julia1.0.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))

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

# prints: hello world

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.

1 Like

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

thanks! The last line code with NamedTuple works ~

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

Why not just

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



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.

1 Like

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

1 Like