I was contributing to a library on Github, and came across the "/" parameter as a function parameter. The function is quite wide and complex, so as not to confuse, I will create a simple one as an example.
def funcion_suma(a, b, /, c, d):
return a + b + c + d
print(funcion_suma(1,2,3,4))
Departure: 10
For a second I thought it was a parameter, but no, the function has 4 parameters a , b , c and d . The slash (/) is simply performing some kind of operation.
Of course, if we define the function without the slash it works just the same and gives the same result:
def funcion_suma(a, b, c, d):
return a + b + c + d
print(funcion_suma(1,2,3,4))
Departure: 10
What is this kind of syntax for?
Explanation of the problem
It is a new syntax that can be used in function parameters. It has been added in Python 3.8 so it doesn't work in previous versions.
It is used to indicate that some function parameters must be specified exclusively positionally (postal argument) and can NOT be passed as key arguments (keyword arguments).
In the above function, a and b are positional arguments, while c and d can be key or positional arguments. In short, everything before the slash ( / ) becomes a positional-only argument , the rest of the arguments after the slash retain whatever type of argument they are (positional, key, arbitrary).
In such a way that if in the previous function we try to pass a or b as key arguments, it will give us the following
TypeError
:Input:
Output:
However, if we pass a and b as positional arguments, everything is correct, since they have been defined as exclusively positional arguments .
Input:
Output:
Possible use cases.
C
which increases speed by making code inC
and in Python compatible ( read PEP399 ).len()
, is defined by Python in the following waylen(obj, /): #etc...
so as not to mislead with the obj parameter .Output:
All this information and more can be found in the Python Enhancement Proposals (PEP) documentation, specifically in PEP570 and also in a more summarized form in What's New In Python 3.8