Check whether a variable is defined

is there a simple check to see whether a variable is defined?

Just do isdefined(:var)

3 Likes

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

Interesting. I never knew that it had this issue. I would like to see this in Base.

2 Likes

I’ve not really found it that useful for anything aside from writing tests that check whether a macro expansion works correctly, i.e.

function my_test()
    @my_macro arg1 arg2
    @test @isdefined generated_var
    @test @isdefined other_generated_var
end

so probably not worth adding to Base just for that.

I guess it really depends what @Diger is needing to do with isdefined, but in “normal” code I’d try to avoid needing to doing any kind of control flow based on whether a variable is defined or not.

2 Likes

Sorry for my late answer. What does
quote
…
end
mean ?
Also why do u wrap a function around “everything” ??
isdefined(:x) does work for my purposes.
In which sense however do u mean doesn’t it work?
I see that in your first example where u wrap isdefined in a function it gives false when u use it with integers instead of symbols, while isdefined(1) or isdefined(:1) would give you an error…

For anyone coming back to this today,
in the post julia 1.0 world.

There now exists a macro that checks if a variable is defined in the current scope.
@isdefined, and it does not do so via the throwing and catching of errors, so it not hideously slow.

31 Likes

I read all the stuff, but it was still not clear to me how to test if the variable Conda.ROOTENV exists.
The documentation was not sufficient for me, I tried a lot of variants also with the macro @isdefined
and in the end, I think I succeeded:

using Conda
isdefined(Conda, :ROOTENV)
1 Like