How do you get all variables with a value in module's workspace?

question

#1

for example,

I have the module:

module Foo

  bar() = println("moo")
  baz() = 404

  a = 2
  b = 3.4e2
  c = a + b / baz()

end

how do i get a dictionary that looks like:

{
  a: 2
  b: 3.4e2
  c: 2.8415841584
}

// note this dictionary ignores (direct definitions of) bar and baz


#2
julia> Dict(s=>eval(Foo, s) for s in names(Foo, true) if s != :Foo && s != :eval && !isa(eval(Foo, s), Function) && !startswith(string(s), "#"))
Dict{Symbol,Real} with 3 entries:
  :c => 2.84158
  :a => 2
  :b => 340.0

#3

Do not use eval here, use getfield instead.


#4

Ah, good point. I actually didn’t know about using getfield with a module.

This works too:

julia> Dict(s=>getfield(Foo, s) for s in names(Foo, true) if s != :Foo && s != :eval && !isa(getfield(Foo, s), Function) && !startswith(string(s), "#"))
Dict{Symbol,Real} with 3 entries:
  :c => 2.84158
  :a => 2
  :b => 340.0

#5

that’s awesome!

is s != :eval needed, though?

it looks like !startswith(string(s), "#")) catches that.

were you just trying to be explicit?


#6

It’s probably just an artifact of the order in which I added the checks while figuring it out. I’m not surprised that one of them is redundant.


#7

the code I got working with my project was:

Dict(s=>getfield(Foo, s) for s in names(Foo, true) if s != :Foo && !startswith(string(s), "#") && !startswith(string(s), "/") && !isa(getfield(Foo, s), Function) && !isa(getfield(Foo, s), Type) && !isa(getfield(Foo, s), Module))

beyond original question, this also ignores:

  • macros
  • types
  • modules
  • loaded files

please shout out any more suggestions you have or cleaning tips