Is there a built in macro like @show that returns a string?

I want the macro @show but to return a string instead of printing. Does something like that already exist?

Not that I know of, but it would be pretty easy to write this by copying the @show definition. e.g.

macro showstring(exs...)
    args = []
    for ex in exs
        push!(args, sprint(Base.show_unquoted, ex), " = ", esc(ex), '\n')
    return :(string($(args...)))

Why do you need such a macro? Seems a little odd to me.

You might be interested in the repr function. It doesn’t have the pretty x = ... part but that’s easy to do manually and not a difficult macro otherwise.

julia> "x = " * repr(rand(1:10,2,3))
"x = [9 6 3; 8 4 5]"

Thanks. Well, among other things, I thought it might be handy when using @assert. The second argument in @assert isn’t very flexible: it’s just a string, but I’d really like it to automatically show everything in the expression. I didn’t want to replace @assert because in the docs it says: “An assert might be disabled at various optimization levels.” which is a good thing. I suppose I could implement my own mechanism to deactivate my @assert replacement. Actually, that might be ideal.

But, I regularly find myself a bit frustrated with functions that print instead of returning a string… So, maybe what I need is a macro that converts a function that takes an IO as first arg to return a string.

You don’t need a macro for this. That’s exactly what the sprint function does. Or, at a lower level, you can print to an IOBuffer and then take! that to a string — this is how sprint is implemented.

1 Like

Thanks! I thought I had just run across something that does that but I couldn’t find it again.