What is a good design for a settable global with a known type?

In a package, I have a const s = "" that is used in a couple of functions. One of these functions doesn’t have a way for a user to specify a different string to use instead. What is a good way to make the value settable?

a::String = ""
set_a(s) = global a = s

const b = Ref("")
set_b(s) = b[] = s

# The real variable is luckily an actual string
ENV["c"] = ""
set_c(s) = ENV["c"] = s

That’s what scoped values are for:

They allow you to keep the global constant but still be able to change its value :grin:.

julia> using Base.ScopedValues

julia> const s = ScopedValue("")
ScopedValue{String}("")

julia> with(s => "lorem") do
           s[]
       end
"lorem"

julia> s[]
""

Currently they’re not optimized very well by the compiler, so even access (s[]) may be too costly. Caveat emptor.

2 Likes

Maybe Preferences.jl could also be useful?

2 Likes

What if you define the local instances as a named parameter with the default value set to the global value?

This fits the use case better! Thanks :smiley: