Invoke a method

question

#1

Is it possible to invoke a Method? Ie suppose I picked one from the MethodList returned by methods, and I want to invoke that particular method with given arguments. Eg

m=which((+),(Int,Int))
# now how to call m with (1,2)?

I tried simply calling it as m(1,2), but apparently Method is not callable per se.


#2

invoke? [21 chars…]


#3

how do I use that?

julia> invoke(which((+),Tuple{Int,Int}),1,2)
ERROR: TypeError: Method: in invoke, expected Type{T}, got Int64

the help for invoke suggests that I could omit the type sig, but I could not make it work even with that:

julia> invoke(which((+),Tuple{Int,Int}),(Any,Any),1,2)
ERROR: MethodError: objects of type Method are not callable

Using v"0.5.0".


#4

Call invoke on the function, not the method:

invoke(+, Tuple{Int,Int}, 1,2)

#5

@mauro3: I am aware of this, I was just asking how @kristoffer.carlsson proposed to do use it. So now we are back to square 1 - see the original question above.


#6

Ok, I missunderstood your question then.


#7

I think the answer then is: “not really”.

Maybe this hack works for you:

julia> stripT(T) = Tuple{T.parameters[2:end]...}

julia> invoke(getfield(m.module, m.name), stripT(m.sig), 1,4)
5

#8

I’ve proposed a number of times making methods more first class – being able to directly call invoke on a method object would be a significant part of that. If you’re feeling like making a PR to Julia, this would be a good one. If not, you could open an issue requesting such a feature.


#9

See also Proposal for a first-class dispatch wrapper for a related proposal.


#10

@StefanKarpinski @jameson Thanks for the pointers. While I don’t doubt that first-class methods would be useful in some applications, in my particular use case I decided that they would be a very convoluted and unidiomatic solution.

What I wanted to do is basically the following: have a DataFrame-like object which is basically a Dict{Symbol,Vector}. I was looking for a way to map vectors using user provided functions, and looking up the vectors dynamically. For example, suppose the user supplies a function f(b,a). The map function would look up :a and :b in the Dict, assign them to positions 2 and 1, and call broadcast with f and the vectors in the right place. I asked about argument name extraction here. The inspiration was Mamba’s implementation of this.

I am currently of the opinion that this is unnatural in Julia, since each function can have many methods, so I could have multiple matches. I could of course apply some kind of dispatch machinery to select the “most specific” one based on the type signature, but in the end I concluded that this is confusing and error-prone, and the DataFramesMeta.@with is a much more natural solution.