Using @printf to generate strings from format in Variable (maybe even in older Julia versions)

I am struggling a little bit with how to use @printf within my code (maybe even functioning in Julia 1.4).

Consider the following minimal example, where I have a stream and the format given in some variables (in the concrete examples fields of a struct)

using Printf
io = stdout
f = "A %f"
@printf io "A %f" 1.0 # works
@printf io f 1.0 # does not work

On Julia 1.7 (and 1.6 but not earlier) I can do

Printf.format(io, Printf.Format(f), 1.0)

But this does neither work on Julia 1.4 or 1.5 – which – if possible – I would like to further support for sure. Any ideas how to get this last line work with @printf directly (or a similar idea) ?

This works for me. It does not work without interpolating f or without the @eval

julia> @eval @printf io $f 1.0
A 1.000000

I do not understand this as metaprogramming is far above my pay grade. I figured this out by trial and error and randomly poking around in the manual. Tested on 1.7.2. I think it’s been working for me since 1.3.

1 Like

Maybe you are right and this is even the only way to got – then (I think) I might bump dependency to Julia 1.6 just to be safe and not use eval. I checked and your solution does work on 1.4 though.

This not working is entirely to be expected from @printf being a macro – it depends on the variable being named f, but not on the value associated with f.

This definitely seems like a case where you want the functionality, but without the limits of the macro. The easiest thing is to impose the version requirements or to backport logic manually for yourself.

1 Like

Since I do also not see a way avoiding eval, it seems to be reasonable to set the lower bound to the current LTS, yes.