Alex A.
Alex A.

Reputation: 5586

View user-defined variables in 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?

Upvotes: 8

Views: 1500

Answers (3)

BVPs
BVPs

Reputation: 161

For Julia v0.7.0 and up, there's a nice function varinfo, which is more or less equivalent to MATLAB's whos function. varinfo still lists some module names like Base, Core, etc., but in a much more compact manner than Julia's old whos function. It also uses Markdown to render the variable table nicely, e.g.,

    julia> varinfo()
    name                    size summary
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––------
    Base                         Module
    Core                         Module
    InteractiveUtils 164.866 KiB Module
    Main                         Module
    Plots             21.028 MiB Module
    ans                144 bytes 13-element Array{Symbol,1}
    x                   48 bytes 20-element StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}
    y                   48 bytes 20-element StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}
    y0                 440 bytes 50-element Array{Float64,1}
    y1                 440 bytes 50-element Array{Float64,1}
    z                  3.164 KiB 20×20 Array{Float64,2}

Upvotes: 5

Alex A.
Alex A.

Reputation: 5586

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.

Upvotes: 5

musically_ut
musically_ut

Reputation: 34288

Julia has whos function, akin to MATLAB, for this task.

Upvotes: 2

Related Questions