What does the /
mean in Python 3.4\'s help
output for range
before the closing parenthesis?
>>> help(range)
H
Forward Slash (/) indicates all arguments prior to it are positional only argument. Positional only arguments feature was added in python 3.8 after PEP 570 was accepted. Initially this notation was defined in PEP 457 - Notation for Notation For Positional-Only Parameters
Parameters in function definition prior Foraward slash (/) are positional only and parameters followed by slash(/) can be of any kind as per syntax. Where arguments are mapped to positional only parameters solely based on their position upon calling a function. Passing positional-only parameters by keywords(name) is invalid.
Let's take following example
def foo(a, b, / , x, y):
print("positional ", a, b)
print("positional or keyword", x, y)
Here in the above function definition parameters a and b are positional-only, while x or y can be either positional or keyword.
Following function calls are valid
foo(40, 20, 99, 39)
foo(40, 3.14, "hello", y="world")
foo(1.45, 3.14, x="hello", y="world")
But, following function call is not valid which raises an exception TypeError since a, b are not passed as positional arguments instead passed as keyword
foo(a=1.45, b=3.14, x=1, y=4)
TypeError: foo() got some positional-only arguments passed as keyword arguments: 'a, b'
Many built in function in python accept positional only arguments where passing arguments by keyword doesn't make sense. For example built-in function len accepts only one positional(only) argument, Where calling len as len(obj="hello world") impairs readability, check help(len).
>>> help(len)
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
Positional only parameters make underlying c/library functions easy to maintain. It allows parameters names of positional only parameters to be changes in future without risk of breaking client code that uses API
Last but not least, positional only parameters allow us to use their names to be used in variable length keyword arguments. Check following example
>>> def f(a, b, /, **kwargs):
... print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3) # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}
Positional only parameters is better Explained here at Types of function arguments in python: Positional Only Parameters
Positional-only parameters syntax was officially added to python3.8. Checkout what's new python3.8 - positional only arguments
PEP Related: PEP 570 -- Python Positional-Only Parameters