Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if a variable is defined inside a module in Julia?

Tags:

julia

isdefined(:x) will tell you if a variable x is defined in your current workspace.

If I want to check a variable is defined in a module (not one that's exported), how can I do that? I tried all of the following:

julia> module Test
       x = 1
       end
Test

julia> x
ERROR: UndefVarError: x not defined

julia> isdefined(:x)
false

julia> Test.x
1

julia> isdefined(:Test.x)
ERROR: type Symbol has no field x

julia> isdefined(:Test.:x)
ERROR: TypeError: getfield: expected Symbol, got QuoteNode

julia> isdefined(Test.:x)
ERROR: TypeError: getfield: expected Symbol, got QuoteNode

In the module Test above, I want to check if x is defined or not.

like image 796
David Parks Avatar asked Jun 14 '16 23:06

David Parks


3 Answers

isdefined has an optional parameter for doing this. Try:

isdefined(Test, :x)

More information available through the usual channels: ?isdefined on the REPL and in the book: http://docs.julialang.org/en/release-0.4/stdlib/base/#Base.isdefined (link may be for older version, so the currently dominant search engine will help).

like image 73
Dan Getz Avatar answered Oct 17 '22 15:10

Dan Getz


I think you need

:x in names(Test) 
like image 33
David P. Sanders Avatar answered Oct 17 '22 15:10

David P. Sanders


In Julia 1.1.0, isdefined's first parameter is not optional, instead there is a macro @isdefined(x) or @isdefined x that tests if x is defined. Calling it inside Test, checks if x is defined when in Test (inherited or not).

See documentation.

like image 1
vinnief Avatar answered Oct 17 '22 16:10

vinnief