Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of variables in the current namespace in Julia

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.

like image 656
Shep Bryan Avatar asked Nov 27 '25 02:11

Shep Bryan


1 Answers

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
like image 86
Przemyslaw Szufel Avatar answered Nov 29 '25 19:11

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!