Is there any way to obtain the parameter types for a given method? For example, if I have function f(x::Int64) x end, is there a way to recover the type of parameter x? I realize that generic methods may make this complex or impossible but I thought I’d ask.
That’s not a well posed idea in Julia because functions can have as many heterogeneous methods as you like.
julia> f(x::Int) = x + 1
f (generic function with 1 method)
julia> f(s::String) = length(s)
f (generic function with 2 methods)
julia> f(v::Vector) = v'v
f (generic function with 3 methods)
julia> f(1), f("hi"), f([1,2,3])
(2, 2, 14)
Only methods have ‘parameters’, though we prefer the term signature here.
julia> methods(f)
# 3 methods for generic function "f":
[1] f(x::Int64) in Main at REPL[5]:1
[2] f(s::String) in Main at REPL[6]:1
[3] f(v::Vector{T} where T) in Main at REPL[7]:1
Methods themselves aren’t really first-class objects in julia though, so there’s no blessed api to ask a specific method what it’s signature is.
Depending on your usecase however, one thing you could use is hasmethod, e.g.
My original question? It’s a bit niche but I have a situation where the package user can pass a function. To make this as ergonomic as possible for the user, I’d like to write it such that the function will take either one of the JSON types (array, string, object/dict etc), or a struct that the JSON is expected to parse to, as its only argument. The JSON can then be parsed in advance into the appropriate type. But obviously this requires me to be able to find the function’s parameter type.