Now that you’ve seen keyword-only arguments, let’s take a look at positional-only arguments. This is valid as of Python version 3.8. You can use a bare slash (
/), similar to the bare asterisk (
*) in the previous lesson, to indicate what parameters must be supplied positionally. In this example, where we define a simple function
f() to take three parameters and display them one at a time, the use of the
/ indicates that
y must be provided positionally.
I can specify
z as a keyword argument, and that works! However, if I try to specify
x as the keyword argument and
y, as well as
z, I get an error telling me that we tried to pass positional-only arguments as a keyword argument.
And you can actually mix positional-only arguments and keyword-only arguments in the interface for a function. You specify the required positional arguments first, followed by the slash, then arguments that can be positional or keyword, and then an asterisk, and then following those, only arguments that can be passed using a keyword. I’ll call it
g() here since I already have a function
f() defined, but it’s going to take two positional-only arguments.
But I get the error that
y must be positional. I can’t supply it as a keyword. And if I try to supply
b as positional arguments, I get a similar error that I provided more positional arguments than was expected.
This gives me a way to really fine-tune my interface to my function to specify what must be positional and what must be keyword. So again,
y must be provided positionally,
b must be provided using keywords, and in this example,
w can be provided in either way.
Become a Member to join the conversation.