Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a Method in Julia

Tags:

julia

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?

like image 746
Georgery Avatar asked Nov 14 '20 15:11

Georgery


People also ask

How do I delete an object in Julia?

You can remove the variable and free up it's memory by calling clear!() . As DFN pointed out, this won't actually remove the objects but set them to nothing . This is useful for freeing up memory from you workspace as you can "delete" the memory footprint for non-constant objects.

How do you remove an element from a list in Julia?

Julia allows to delete an element from a 1D array by using predefined function pop!. This function will simply remove the last element of the array and reduce the array size by 1. To delete first element of the array, one can use popfirst! function.

What is a method in Julia?

The choice of which method to execute when a function is applied is called dispatch. Julia allows the dispatch process to choose which of a function's methods to call based on the number of arguments given, and on the types of all of the function's arguments.


Video Answer


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)
like image 140
Georgery Avatar answered Oct 21 '22 06:10

Georgery


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.

like image 42
tholy Avatar answered Oct 21 '22 06:10

tholy