有什么方法可以获取模块中定义的功能列表? [英] Any way to get a list of functions defined in a module?

查看:102
本文介绍了有什么方法可以获取模块中定义的功能列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何内省性的魔法可以为我提供模块中定义的功能列表?

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)

哪个会返回:[foo,bar]

Which would return: [foo,bar]

推荐答案

此处的问题是nameswhos都列出了模块中的导出的名称.如果您想看到它们,则需要执行以下操作:

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

此时nameswhos都将列出所有内容.

At this point both names and whos would list everything.

如果您恰巧在REPL上工作,并且由于任何原因不想导出任何名称,则可以通过键入Foo.[TAB]交互地检查模块的内容.查看此会话中的示例:

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

以某种方式,制表符补全会查找未导出的名称,因此必须 可以让Julia告诉您.我只是不知道那个功能是什么.

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.

我做了一些挖掘.未导出的功能Base.REPLCompletions.completions似乎可以正常工作,正如我们先前使用的REPL会话的延续所证明的那样:

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"

这篇关于有什么方法可以获取模块中定义的功能列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆