Printing names and values of a number of variables

I am looking for a julia function that can print both the
names and the values of a sequence of variables, as per the following example:
#Define a number of variables (could be any number)
s1 = 123
s2 = " s g ny ny ny uuy nhneejn"
s3 = 123.4567890
#Print their names and values using a custom
#julia function my_display(), taking a
#variable number of arguments, as follows.
my_display(s1,s2,s3)
s1 = 123
s2 = " s g ny ny ny uuy nhneejn"
s3 = 123.4567890

I have found a primitive way of doing this as follows.
my_display([:s1,s1,:s2,s2,:s3,s3])

Any other solutions that are more elegant and
general would be appreciated.

No function can do this, but it’s a trivial example of a macro:

import Printf: @printf

macro names_values(vars...)
    lines = Any[]
    for var in vars
        push!(lines, :(@printf("%s = %s\n", $(QuoteNode(var)), $(esc(var)))))
    end
    quote
        begin
            $(lines...)
        end
    end
end

let x = 11, y = 21, z = 31
    @names_values(x, y, z)
end
1 Like

Seeing how a relatively simple macro can be written is instructive, but note that the built-in @show does exactly the same

julia> let x = 11, y = 21, z = 31
           @show(x, y, z)
       end;
x = 11
y = 21
z = 31
7 Likes