is there a simple check to see 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
How to check whether a identifier is defined within the current scope?
Interesting. I never knew that it had this issue. I would like to see this in Base.
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.
Sorry for my late answer. What does
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…