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.
No requirement is made on
z. It could be provided positionally or using a keyword. If we want to see that in action,
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.
/ means that the following aren’t positional-only, then the
* means those that follow must be provided positionally. And we’re just going to print them out.
We’re not interested in the body of this function. We’re interested in seeing how to call a function with those requirements. So, I can specify values for
y, I must do so positionally.
I could choose to provide parameters for
w positionally, but
b have to be specified with a keyword argument.
I do have the option, however, to specify
w using keyword arguments,
but I can’t specify
y with a keyword argument, and once I specify one keyword argument, I have to provide all of the others using keywords.
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.
04:13 Next, we will start taking a look at other aspects of writing functions, and those are about documentation: communicating to other programmers what your function does and how best to use it.
Become a Member to join the conversation.