Delete a Method in Julia

Viewed 237

I have a function with 2 methods

function foo(a::Integer) 42 end
function foo(a::String) 24 end

foo(2)
42

foo("a")
24

How can I delete just one of the two methods?

2 Answers

There is a type Method. Instances of that type refer to a specific method of a particular function.

particular_method = @which foo(2)
foo(a::Integer) in Main at /home/js/Documents/Julia/Matching/Query_Creation.jl:75

typeof(particular_method)
Method

And here's a way to delete the method using such an object:

Base.delete_method(particular_method)

foo(2)
ERROR: MethodError: no method matching foo(::Int64)

If you're writing your code in a file tracked by Revise, then deleting the method in the source will delete it in your running session. If I copy your two definitions to a file /tmp/delmeth.jl, then

julia> using Revise

julia> Revise.includet("/tmp/delmeth.jl")

julia> foo(2)
42

julia> foo("a")
24

Now, in your editor, delete the method for foo(::String), save the file, and in the same session do this:

julia> foo(2)
42

julia> foo("a")
ERROR: MethodError: no method matching foo(::String)
Closest candidates are:
  foo(::Integer) at /tmp/delmeth.jl:1
Stacktrace:
 [1] top-level scope
   @ REPL[6]:1

If you're developing anything "serious" & reusable, then you should generally create packages, in which case you don't need includet because Revise automatically tracks packages that you've loaded with using or import. See the Revise docs for further details.

Related