Check whether a variable is defined

isdefined will only work within the global scope of a module, i.e. the result of

julia> function test(x)
           isdefined(:x)
       end
test (generic function with 1 method)

julia> test(1)
false

might not be what you expect it to be.

If you need something for local scopes as well then try the following macro:

julia> macro isdefined(var)
           quote
               try
                   local _ = $(esc(var))
                   true
               catch err
                   isa(err, UndefVarError) ? false : rethrow(err)
               end
           end
       end

And then use it like so

julia> function test(x)
           @isdefined x
       end
test (generic function with 1 method)

julia> test(1)
true
9 Likes