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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With