Deprecating usage of keywords


#1

In Optim (https://github.com/JuliaOpt/Optim.jl/pull/304) I am currently deprecating our old keyword based options system in favor of the Optim.Options (earlier OptimizationOptions) approach.

Say I used to have the following methods

function myfun(a, b, c, o)
    ... do stuff ...
end
function myfun(a, b, c; d = 1, e = 2)
    myfun(a, b, c, Options(d = d, e = e))
end
function myfun(a, b; d = 1, e = 2)
    myfun(a, b, C(), Options(d = d, e = e)
end

Now, to avoid breaking too much code in the wild, I want to deprecate it. In the future, I want

function myfun(a, b, c, o)
    ... do stuff ...
end
function myfun(a, b, c)
    myfun(a, b, c, Options()
end
function myfun(a, b)
    myfun(a, b, C(), Options()
end

My problem is: how do I tell someone who runs myfun(A(), B(); d = 44) that I want them to use myfun(A(), B(), Options(d = 44)? If I deprecate myfun(a, b; kwargs...) it will also throw the warning when people use myfun(a, b), and that is not what I want!

Also, in some other code unrelated to “myfun” (which is actually optimize) I want to deprecate the name of a keyword, how do I do that? I want to deprecate ABC(; keyword! = default_value) in favor of ABC(; keyword = default_value).

Thanks!


#2

Perhaps something custom:

julia> const has_deprecated_kw_old = Ref(false)
Base.RefValue{Bool}(false)

julia> function f(;kw_new = nothing, kw_old = nothing)
           if kw_old !== nothing
               kw_new = kw_old
               if !has_deprecated_kw_old[]
                   warn("kw_old keyword is deprecated, please use kw_new")
                   has_deprecated_kw_old[] = true
               end
           end
           print(kw_new)
       end
f (generic function with 1 method)

julia> f(kw_old="foo")
WARNING: kw_old keyword is deprecated, please use kw_new
foo
julia> f(kw_old="foo")
foo
julia> f(kw_new="foo")
foo

#3

Ah, of course. I thought about checking the value of the old keyword, but didn’t think about changing it to nothing. When I thought about it, I wanted to check old_kw == old_default_value, but that won’t fire a warning if someone manually sets that value. Since no one should ever set the linesearch kw to nothing, this would work. Thanks