Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to get a list of functions defined in a module?

Tags:

julia

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]

like image 283
aneccodeal Avatar asked Feb 25 '15 23:02

aneccodeal


People also ask

Which library function returns the list of all functions in a module?

The dir() function The dir() built-in function returns a sorted list of strings containing the names defined by a module. The list contains the names of all the modules, variables, and functions that are defined in a module.

How do you know all the names defined in a module?

The dir() function is used to find out all the names defined in a module. It returns a sorted list of strings containing the names defined in a module. In the output, you can see the names of the functions you defined in the module, add & sub .


1 Answers

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"
like image 114
spencerlyon2 Avatar answered Oct 22 '22 01:10

spencerlyon2