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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
# c, d are positional or keyword
# e, f are 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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0