Is it possible to convert a method to a dictionary (or similar structure) with entries:
Argument_Name => Argument_Type
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
Method
typemethods(f)
we can access all methods of a function f
(in a Base.MethodList
)sig
(signature?) and slot_syms
(names of the arguments?) which could be massaged into a dictionaryExample:
# 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 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 Pair
s 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}
Thanks Sevi
Interesting that its not more easily accessible. You have to split strings etc