specs icon indicating copy to clipboard operation
specs copied to clipboard

Keyword only arguments

Open bsipocz opened this issue 1 month ago • 3 comments

It came up that the generalisation of https://scikit-learn-enhancement-proposals.readthedocs.io/en/latest/slep009/proposal.html could be still useful for some projects (e.g. networkx, cc @rossbar) so it could be a good SPEC candidate especially as there is also tooling involved for the deprecation period.

bsipocz avatar Nov 07 '25 15:11 bsipocz

Indeed - this has been a discussion point in NetworkX and I think the way forward essentially involves adapting SLEP009

rossbar avatar Nov 07 '25 15:11 rossbar

Note: Matplotlib also has a policy on this.

Consider making as many arguments keyword-only as possible.

We also have a deprecation/migration decorator for this _api.make_keyword_only. To migrate from

def func(x, y, foo=1, bar=2, baz=4)

to

def func(x, y, foo=1, *, bar=2, baz=4)

you can simply do

@_api.make_keyword_only("3.11", "bar")
def func(x, y, foo=1, bar=2, baz=4)

which will issue a deprecation warning if any of the following parameters is passed positionally. When the deprecation expires, one simply removes the decorator and adds the kw-only marker to the function.

timhoffm avatar Nov 24 '25 10:11 timhoffm

SciPy is using https://github.com/scipy/scipy/blob/3bec13bfd3a31f83dac8a501c37d1435b988ee8c/scipy/_lib/deprecation.py#L182-L184

lucascolley avatar Nov 24 '25 10:11 lucascolley

Tangential: In scikit-image we also have a similar decorator to replace positional arguments with keyword-only ones. : https://github.com/scikit-image/scikit-image/blob/bcec52560ba38981fbb0a05b92979fb840b2c712/src/skimage/_shared/utils.py#L216-L394 😄

from skimage._shared.utils import deprecate_parameter, DEPRECATED
@deprecate_parameter(
    "b", new_name="c", start_version="0.1", stop_version="0.3"
)
def foo(a, b=DEPRECATED, *, c=None):
    return a, c

We've only transitioned from positional to keyword-only when we were renaming a parameter anyway for different reasons. So the decorator expects that. DEPRECATED is a sentinel value that behaves nicely in context of Sphinx generated HTML and also in source code.

lagru avatar Dec 02 '25 15:12 lagru