Bare Forward Slash In Python Function Definition?
Solution 1:
Introduction as syntax
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.
Comparison of syntax and annotational PEPs
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
- Defines the syntax of Python 3.8+
- Formal grammatical specification of the syntax
- Type: Accepted
PEP 457 -- Notation For Positional-Only Parameters
- Defines notation (not syntax) used in
help()
annotations - Informal English language description
- Type: Informational
- Defines notation (not syntax) used in
Explanation and example
There 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:
defpow(x, y, z=None, /):
r = x**y
if z isnotNone:
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)
Post a Comment for "Bare Forward Slash In Python Function Definition?"