Bare Variable Argument Parameter
00:00 Let’s take a look at another example using keyword-only arguments. Here’s an example of a calculation function that we want to provide two arguments and an operation code, and it will perform that operation on the two numbers provided.
If we provide an operation code of plus (
'+'), it will add the two numbers, if I provide an operation code of minus (
'-'), it will subtract, and this one just has addition, subtraction, and division.
00:29 You can imagine this being more complicated if we were wanting to write a practical calculation function, but we’re just using this function to demonstrate keyword-only arguments, so we don’t need to implement a full version of this function.
But right now, I’ve not done anything that specifies the operation code must be provided with a keyword. I can say
4, and then use the division symbol (
"/") for the third argument, and it performs the division. So, what can we do? Well, something we can try: Remember from our last lesson, if we, after specifying some positional parameters, specify some tuple packing, any remaining positional parameters will be packed into this tuple called
ignore, and then the operation code would have to be specified using a keyword.
I’m calling this
ignore instead of
args because I am not actually going to use what’s here in the body of my function. So I don’t need a common name for it. In fact, saying
ignore highlights the fact that whatever remaining positional parameters there are are going to be ignored. Let me go ahead and save this, and let me restart my REPL here.
03:01 and subtraction. Addition works by default. But now I can do some unusual things that really don’t make sense. I can put in an additional positional parameter that’s going to be packed into the tuple that’s ignored, so I still am going to do division in this case.
But even more unusual, if I accidentally try to specify the operation code argument positionally, I’m going to get addition again because in this case, the slash (
"/") was also packed into that tuple.
I get an error message. This extra positional parameter
"what" doesn’t belong there. And so instead of the function working and wondering what this third positional parameter meant, I actually do get an error message informing me that I’ve tried to call that function incorrectly.
05:41 And again, same thing if I try to provide the operation code as a positional parameter. So now we have a function that requires two positional parameters for the two argument values we want to operate on, and as a keyword parameter, the value for the operation code, and now that operation code must be specified using a keyword.
Become a Member to join the conversation.