Assign only if not already defined in Julia

You can use the @isdefined macro: (@isdefined x) || (x = NEW_VALUE).


I've prepared a macro to deal with that little inconvenience.

macro ifund(exp)
    local e = :($exp)
    isdefined(Main, e.args[1]) ? :($(e.args[1])) : :($(esc(exp)))   
end

Then in REPL:

julia> z
ERROR: UndefVarError: z not defined

julia> @ifund z=1
1

julia> z
1

julia> z=10
10

julia> @ifund z=2
10

julia> z
10

An example of interpolation:

julia> w
ERROR: UndefVarError: w not defined

julia> w = "$(@ifund w="start:") end"
"start: end"

julia> w
"start: end"

But, remember of the scope (y is in the scope of for-loop):

julia> y
ERROR: UndefVarError: y not defined

julia> for i=1:10 y = "$(@ifund y="") $i" end

julia> y
ERROR: UndefVarError: y not defined

Let me know if it works. I'm curious, because it's my first exercise with macros.

edited: Julia v1.0 adaptation done.

Tags:

Julia