Home > database >  Get list of variables in the current namespace in Julia
Get list of variables in the current namespace in Julia

Time:04-25

I have a question that is similar to, but different than this one. I have a function within a module, and I would like to see what variables are defined inside the function namespace. In the other post, they said to use varinfo, but that seems to only work in the Main namespace. For example if I run this

module Test

function hello()
    a = 1
    varinfo()
    return a
end

end

import .Test

Test.hello()

I get this error

WARNING: replacing module Test.
ERROR: UndefVarError: varinfo not defined

Is there a way to get a list of variables within a given namespace? What I am looking for is a function that when called, outputs all the available variables (a in my example) as well as available modules within the namespace.

PS. I would like to add, that varinfo is incredibly limiting because its output is a Markdown.MD, which cannot be iterated over. I would prefer a function that outputs variables and values in some sort of list or dictionary if possible.

CodePudding user response:

varinfo is showing only the global variables. If you want the local variables, you need to use the Base.@locals macro:

module Test
    function hello()
        a = 1
        println(Base.@locals)
        return a
    end
end

And now you can do:

julia> Test.hello()
Dict{Symbol, Any}(:a => 1)
1

CodePudding user response:

Is this what you want?

module Test

function hello()
    a = 1
    println(Main.varinfo(@__MODULE__; all=true, imported=true))
    return a
end

end
  • Related