In the signature returned interactively by help(foo)
, what is the meaning of a /
?
In [37]: help(object.__eq__)
Help on wrapper_descriptor:
__eq__(self, value, /)
Return self==value.
In [55]: help(object.__init__)
Help on wrapper_descriptor:
__init__(self, /, *args, **kwargs)
Initialize self. See help(type(self)) for accurate signature.
I thought it might be related to keyword-only arguments, but it's not. When I create my own function with keyword-only arguments, positional and keyword-only arguments are separated by *
(as expected), not by /
. What does the /
mean?
As explained here, the '/' as an argument marks the end of arguments that are positional only (see here), i.e. arguments you can't use as keyword parameters. In the case of __eq__(self, value, /)
the slash is at the end, which means that all arguments are marked as positional only while in the case of your __init__
only self, i.e. nothing, is positional only.
Edit:
This was previously only used for built-in functions but since Python 3.8, you can use this in your own functions. The natural companion of /
is *
which allows to mark the beginning of keyword-only arguments. Example using both:
# a, b are positional-only. e,f keyword-only
def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
# valid call
f(10, 20, 30, d=40, e=50, f=60)
# invalid calls:
f(10, b=20, c=30, d=40, e=50, f=60) # b cannot be a keyword argument
f(10, 20, 30, 40, 50, f=60) # e must be a keyword argument