Get function object from method


#1

Given a Method object, how do I get the function it implements? eval(method.module, method.name) works, but it doesn’t look all that reliable.


#2

The first type in sig

julia> m = @which sqrt(1.0)
sqrt(x::Union{Float32, Float64}) in Base.Math at math.jl:454

julia> typeof(m)
Method

julia> m.sig
Tuple{typeof(sqrt),Union{Float32, Float64}}

Note that in general you can only get the type of the function and not the function itself since it can be a closure. If it’s not a closure than the function type should be a singleton type and you can get it’s instance.


#3

One possible way to get the function itself:

m = @which sqrt(1.0)
m.sig.parameters[1].instance(9)  # returns 3.0

This is not a public interface. Set your expectations accordingly.

#with closure [CORRECTION. The following is not a closure. see below]
a = 3
m = @which (x->x+a)(0)
m.sig.parameters[1].instance(9)  # returns 12

#4

No it can’t possibly work for closures. Your x -> x + a is NOT a closure.


#5

You are correct! My mistake.


#6

From private message:

let
    state = 0
    global counter
    counter(x) = state = state + x + 1
end

Is probably a closure in some sense but it’s not really what closure means in this context. This is a normal function that has a local state spliced in. The main difference is that you can’t create multiple independent instances of counters. Also note that I believe this syntax is deprecated on master and will require explicit splicing.