Hi all,
I’m trying to determine if a user has defined all the necessary input variables. I’d like to store the variable names in a list (either a tuple or array) and then be able to cycle through it and check if they’re defined. This seems like it should be simple, but I can’t get the syntax right. I tried various things such as the following, but I get errors like the one below. Any suggestions?
julia> a = 1
1
julia> vlist = (:a, :b)
(:a, :b)
julia> @isdefined(vlist[1])
ERROR: LoadError: MethodError: no method matching var"@isdefined"(::LineNumberNode, ::Module, ::Expr)
Closest candidates are:
var"@isdefined"(::LineNumberNode, ::Module, ::Symbol) at /Applications/Julia-1.7.app/Contents/Resources/julia/share/julia/base/essentials.jl:150
in expression starting at REPL[58]:1
julia> isdefined.(Ref(Main), vlist)
(true, false)
You can use isdefined(@__MODULE__, vlist[1])
instead. I’d encourage you to find a different way to structure your code though; this pattern isn’t (usually) a good idea.
3 Likes
So if I do what @nilshg suggested I get the right results, but I get the following with what @pfitzseb suggested, which seems weird as this is pretty much the same thing:
julia> a
1
julia> b
2
julia> c
ERROR: UndefVarError: c not defined
julia> d
ERROR: UndefVarError: d not defined
julia> isdefined.(Ref(Main), vlist)
(true, true, false, false)
julia> isdefined(Ref(Main), vlist[1])
false
julia> isdefined(Ref(Main), vlist[2])
false
julia> isdefined(Ref(Main), vlist[3])
false
julia> isdefined(Ref(Main), vlist[4])
false
That’s not what I wrote though. You have an extraneous Ref
in there.
1 Like
My apologies… was thinking those would both be pointing to the same thing for the example in the REPL. Yes, they both work fine.
@pfitzseb what exactly is the @MODULE doing?
help?> @__MODULE__
@__MODULE__ -> Module
Get the Module of the toplevel eval, which is the Module code is currently
being read from.
Generally, Ref(x) != x
; when broadcasting, the Ref
“unwrapped”.
1 Like