Search code examples
methodsjuliatype-signature

How to specify the type signature to find a specific method with InteractiveUtils.edit in Julia?


In order to quickly find the implementation of some methods I would like to use InteractiveUtils.edit.

E.g. if I wanted to see the implementation of methodswith I should be able to write something like edit(methodswith). However, as the methodswith function has multiple methods I get:

ERROR: function has multiple methods; please specify a type signature

How do I specify the type signature? I know that I can find out which methods there are with methods(methodswith), giving signatures like this:

[1] methodswith(t::Type; supertypes) in InteractiveUtils at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.0/InteractiveUtils/src/InteractiveUtils.jl:169

How can I plug this into a call of edit?

I know that there is @edit which I could use with some exemplary function call. However, sometimes it would be more straightforward to just specify the types, because constructing the objects for an exemplary call of the method also involves some investigation for valid constructors.

TL;DR:

How to find a specific method of a function with InteractiveUtils.edit in Julia?


Solution

  • Just pass argument types as a tuple in the second positional argument to edit.

    For example edit(sin, (Int,)) will open you the definition of sin that is used with one argument of type Int.

    Note that this might fail if you want to edit a function from stdlib (for functions from Base or non-standard libraries edit will work properly).

    In such a case you have to use methods function and locate the file manually. For example:

    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
    

    Now you have a file name and a line number where the method is located, but the path may be wrong, so you have to find the file yourself in the Julia installation folder.

    Here is how you can retrieve this information programatically (assuming you have specified the args correctly and only one method matches). First define a function:

    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
    

    and now you can write e.g. edit_stdlib(mean, (Vector{Int},)) to get what you want.