Any way to get a list of functions defined in a mo

2019-04-09 07:35发布

Is there any introspective magic that would give me a list of functions defined in a module?

module Foo
  function foo()
    "foo"
  end
  function bar()
    "bar"
  end
end

Some mythical function like:

functions_in(Foo)

Which would return: [foo,bar]

标签: julia
1条回答
Summer. ? 凉城
2楼-- · 2019-04-09 08:14

The problem here is that both names and whos list exported names from a module. If you wanted to see them then you would need to do something like this:

module Foo

export foo, bar

function foo()
    "foo"
end
function bar()
    "bar"
end
end  # module

At this point both names and whos would list everything.

If you happen to be working at the REPL and for whatever reason did not want to export any names, you could inspect the contents of a module interactively by typing Foo.[TAB]. See an example from this session:

julia> module Foo
         function foo()
           "foo"
         end
         function bar()
           "bar"
         end
       end

julia> using Foo

julia> whos(Foo)
Foo                           Module

julia> names(Foo)
1-element Array{Symbol,1}:
 :Foo

julia> Foo.
bar  eval  foo

Somehow the tab completion is looking up un-exported names, so there must be a way to get Julia to tell them to you. I just don't know what that function is.

EDIT


I did a little digging. The un-exported function Base.REPLCompletions.completions seems to work, as demonstrated in a continuation of the REPL session we were previously using:

julia> function functions_in(m::Module)
           s = string(m)
           out = Base.REPLCompletions.completions(s * ".", length(s)+1)

           # every module has a function named `eval` that is not defined by
           # the user. Let's filter that out
           return filter(x-> x != "eval", out[1])
       end
functions_in (generic function with 1 method)

julia> whos(Foo)
Foo                           Module

julia> names(Foo)
1-element Array{Symbol,1}:
 :Foo

julia> functions_in(Foo)
2-element Array{UTF8String,1}:
 "bar"
 "foo"
查看更多
登录 后发表回答