In the Python 3.8 Programming FAQ, I saw the following function definition:
class callByRef:
def __init__(self, /, **args):
for key, value in args.items():
setattr(self, key, value)
This is missing in the Python 3.7 version:
class callByRef:
def __init__(self, **args):
for (key, value) in args.items():
setattr(self, key, value)
What is this new /
syntax?
How does it relate to a /
appearing in help()
output?
Note: this and this question are about help()
annotation, whereas this question is about new syntax and any differences to the help()
annotation.
Use Forward slash / to break code into multiline code. Line break means code line change in Python, but you can use forward slash / to bluff python. You can easily break your code into multiple lines using forward slash in between.
Use the str. split() method to split a string on the forward slashes, e.g. my_list = my_str. split('/') .
There are two ways to pass variable-length arguments to a python function. The first method is by using the single-asterisk (*) symbol. The single-asterisk is used to pass a variable number of non-keyworded arguments to the function.
A function is defined by using the def keyword, followed by a name of your choosing, followed by a set of parentheses which hold any parameters the function will take (they can be empty), and ending with a colon.
The /
as syntax was introduced in Python 3.8.
The rationale for /
in an argument list is given in PEP 570 -- Python Positional-Only Parameters:
The new syntax will enable library authors to further control how their API can be called. It will allow designating which parameters must be called as positional-only, while preventing them from being called as keyword arguments.
Previously, (informational) PEP 457 defined the syntax, but with a much more vague scope. This PEP takes the original proposal a step further by justifying the syntax and providing an implementation for the
/
syntax in function definitions.
Similarities
For all intents and purposes, if you understand help()
's /
notation, then that's what is formally included as Python syntax in v3.8 via PEP 570.
Differences
PEP 570 -- Python Positional-Only Parameters
PEP 457 -- Notation For Positional-Only Parameters
help()
annotationsThere are already excellent answers on the meaning and usage of /
in arguments.
To save you the click through:
A /
means that all preceding parameters are positional-only parameters. Positional-only parameters before a /
cannot be passed as name=value
when calling the function.
Python 3.8 What's New gives the following example:
def pow(x, y, z=None, /):
r = x**y
if z is not None:
r %= z
return r
Valid function calls:
pow(2, 10)
pow(2, 10, 17)
Invalid function calls:
pow(x=2, y=10)
pow(2, 10, z=17)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With