Method to Dict

Is it possible to convert a method to a dictionary (or similar structure) with entries:

    Argument_Name => Argument_Type

I was just curious if/how this would work, here are my findings

  • methods are instances of a Method type
  • with methods(f) we can access all methods of a function f (in a Base.MethodList)
  • the instances of the method (all ?) seem to have the fields sig (signature?) and slot_syms (names of the arguments?) which could be massaged into a dictionary
  • the argument names contain some other stuff and would need to be parsed
  • the signature has the function type itself as the first element

Example:

# Ex 1

julia> sortmethod1 = methods(sort)[1]
sort(r::AbstractUnitRange) in Base at range.jl:1379

julia> sortmethod1.slot_syms
"#self#\0r\0"

julia> sortmethod1.sig
Tuple{typeof(sort), AbstractUnitRange}

# Ex 2

julia> plusmethod = last(methods(+))
+(a, b, c, xs...) in Base at operators.jl:591

julia> plusmethod.slot_syms
"#self#\0a\0b\0c\0xs\0"

julia> plusmethod.sig
Tuple{typeof(+), Any, Any, Any, Vararg{Any}}

I’m really not sure what caveats there might be to this approach or if there are some convenience functions to do this :sweat_smile: it’s fun to do a bit of “reverse-engineering” though.

EDIT: Here is a quick and dirty function that answers your actual question (going for a list of Pairs to preserve the argument order – an OrderedDict might also be convenient):

function get_method_info(method)
    argNames = split(method.slot_syms, "\0")[2:end-1] .|> string
    argTypes = method.sig.parameters[2:end]
    return [n => T for (n, T) in zip(argNames, argTypes)]
end

julia> get_method_info(plusmethod)
4-element Vector{Pair{String}}:
  "a" => Any
  "b" => Any
  "c" => Any
 "xs" => Vararg{Any}
1 Like

Thanks Sevi
Interesting that its not more easily accessible. You have to split strings etc

1 Like