为了快速找到某些方法的实现,我想使用InteractiveUtils.edit
。
例如如果我想看看methodswith
的实现,我应该可以写类似edit(methodswith)
的东西。但是,由于methodswith
函数有多种方法,我得到了:
ERROR: function has multiple methods; please specify a type signature
如何指定类型签名?我知道我可以使用methods(methodswith)
找出哪些方法,并给出如下签名:
[1] methodswith(t::Type; supertypes) in InteractiveUtils at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.0/InteractiveUtils/src/InteractiveUtils.jl:169
如何将其插入edit
的呼叫中?
我知道有@edit
可以与某些示例函数调用一起使用。但是,有时仅指定类型会更直接,因为为方法的示例性调用构造对象还涉及对有效构造函数的一些研究。
TL; DR:
如何在Julia中使用InteractiveUtils.edit
查找函数的特定方法?
答案 0 :(得分:0)
只需将参数类型作为元组传递到edit
的第二个位置参数中。
例如,edit(sin, (Int,))
将为您打开sin
的定义,该定义与类型为Int
的一个参数一起使用。
请注意,如果您要从stdlib编辑功能,则此操作可能会失败(对于来自Base或非标准库edit
的功能将正常运行)。
在这种情况下,您必须使用methods
函数并手动定位文件。例如:
julia> using Statistics
julia> edit(mean, (Vector{Int},)) # this might not work as expected
julia> methods(mean, (Vector{Int},))
# 1 method for generic function "mean":
[1] mean(A::AbstractArray; dims) in Statistics at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.1\Statistics\src\Statistics.jl:132
现在,您在方法所在的位置具有文件名和行号,但是路径可能不正确,因此您必须自己在Julia安装文件夹中找到该文件。
以下是您以编程方式检索此信息的方法(假设您正确指定了args
并且只有一种方法匹配)。首先定义一个函数:
function edit_stdlib(fun, args)
m = methods(fun, args)
@assert length(m.ms) == 1 # assume we have an exact match
p = joinpath(Sys.STDLIB, splitpath(string(m.ms[1].file))[end-2:end]...)
l = m.ms[1].line
edit(p, l)
end
,现在您可以编写例如edit_stdlib(mean, (Vector{Int},))
得到您想要的。