Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View user-defined variables in Julia

Tags:

julia

Perhaps this is something I've simply overlooked in the documentation, but how can you view a list of currently defined variables in Julia? For example, in R you can use ls() which will give you a list of user-defined objects in the current scope. Is there an equivalent in Julia?

This is very similar to this question, but it seems that the whos function (as well as names) will list modules and other things which are not user-defined. How do I simply list variables which have been defined by the user and are not exported from other modules?

like image 618
Alex A. Avatar asked Jun 22 '15 15:06

Alex A.


1 Answers

One possible approach is to make a variant of whos that restricts on the summary of the objects in the current module:

function whos_user(m::Module=current_module())
    for v in sort(names(m))
        s = string(v)
        if isdefined(m, v) && summary(eval(m, v)) != "Module" && s != "whos_user"
            println(s)
        end
    end
end

Then if we do

x = 1
y = "Julia"
f(n) = n + 1
whos_user()

we get

f
x
y

One could also write whos_user to return an array of symbols rather than printing:

function whos_user(m::Module=current_module())
    v = sort(names(m))
    filter(i -> isdefined(m, i) && summary(eval(m, i)) != "Module" && string(i) != "whos_user", v)
end

Then running the same test code as before, we get this:

3-element Array{Symbol,1}:
  :f
  :x
  :y

If there's no better way to do this then I'll accept this answer.

like image 138
Alex A. Avatar answered Sep 24 '22 00:09

Alex A.