Use keyword in the upcomming keywords

question

#1

Hello, I know that it is allowed to use keyword arguments to define later arguments like, e. g., this:

f(;a=1, b="$a") = b

Now calling

f()
f(;a=2)

works fine. However I cannot write this one:

f(;a=3, b="$a")

which complains that a is not defined.

Is it a design issue or a bug and is there a way to circumvent this.
(Of cause I can define a before the call and than use it in the call but this results in additional variable which I actually do not need beside for this call).


#2

You are in the second case creating the full string (evaluating the “$a”) before it is passed on to the function. If you do not have an a in your namespace, then this will error before the function call was ever made.

I would not guess that you can circumvent this. And I am not entirely sure why you would want to? b gets a value from a if you do not try to pass this.


#3

The real case is kind of more complicated. Something like this:

f(;a=1, b=2, c=3, filename="default_$(a)_$(b)_$(c).dat") = ...

and call it later with

f(;a=4, b=5, c=6, filename="something_different_$(a)_$(b)_$(c).dat") 

It would have been really nice if that would be possible. But I agree, I don’t thing it is.


#4

I see the problem. In your particular example, you could add another argument for the name_prefix="default", but I do not know of a general solution to your actual question.


#5

Also, you could do

a = 4
b = 5
c = 6
f(a=a, b=b, c=c, filename="something_different_$(a)_$(b)_$(c).dat")

But, again, I don’t know how to delay the string interpolation util the function has been called.


#6

Yes, both ways are known to me :wink: Thanks. The first one restricts me to have a fixed structure of the string and the second is exactly this definition of dummy variables… But yeah, I do it in this way… Probably one could pass an Expr and then @eval it but this would result in a global variable.


#7

Passing the a keyword does not create a local a variable in the caller. Even though it uses the = syntax or does something quite distinct.