00:12 Starting with Python 3, you can specify that a parameter can only be supplied with a keyword argument. One instance where you might want to use this is if you have a function that takes a collection as positional arguments, but other parameters have a specific purpose.
00:32 The use of keyword arguments will prevent the ambiguity between which are the special purpose parameters and which are your positional arguments that your function is going to treat as that collection.
00:45 So, here is a simple function that’s going to take a collection, hopefully of strings, and display them with a decimal point between them, and all of that preceded by this prefix, and the prefix is what this example is going to be taking a look at.
But just to see how this function operates… We’re going to call it
concat(), and it works on a collection, which should be provided as simply a set of positional parameters that will be strings. And we’re going to print it!
We’re going to use an arrow (
'->') as a prefix, and then we’re going to use the string method
.join() to take all of the strings provided as a parameter and separate them by the decimal point between the quotes.
.join() method simply attaches them all together separated by whatever string we provided here, which was the decimal point. But now we would like to allow, should someone using this function wish to, to replace the arrow with some other prefix.
And that works too. But with this version, the prefix is no longer optional. I can’t just say
concat('a', 'b', 'c') and get the arrow. Now
'a' has become the prefix. Notice there’s not a dot here, it is our prefix to
'c'. In fact, if I included some more here, it might be more noticeable that there isn’t a dot between the
'a' and the
And so recalling this function call, we get the prefix of the hyphen as expected. And if I leave the prefix out? Well, no, that didn’t work. It took
'a' to be the prefix, because that was the first parameter.
We could try specifying a value for
prefix. So, we say
concat(prefix='//', 'a', 'b', 'c'), but it doesn’t like that. We get a
SyntaxError that the positional argument was following a keyword argument. So the keyword argument has to be last, so let’s try that.
And now if we specify just positional arguments, we get the default parameter. But if I specify some other prefix, I have to do it using the keyword, otherwise, in the last example, it would have just taken
'c' as the prefix, but I can specify using a keyword only that we would like the prefix to be, in this case,
Become a Member to join the conversation.