Writing a Positional-Only Function
00:00
All right. So what’s the new thing that we wanted to talk about here? Right, new is in parentheses, because at least the slash (/
) here was 3.8.
00:10
The star (*
) might have been earlier, but Python 3.8 is really when all this sort of comes together.
00:18
So looking at the first function here, positional_only()
, putting the /
as if it were the last parameter in this function definition means that every parameter before that needs to be positional. So it can’t be a keyword argument.
00:34
And that’s kind of a strange syntax that you don’t really see much in Python, like just the slash used as an argument. Right. You might want to, you know, like put quotes (""
) around it or something like that if you see it like this, but that’s actually valid syntax starting from 3.8 upwards.
00:51
Exactly. Yeah. You might be tempted to do that, but it’s—the error you get if you try to call the function with a keyword argument, you get a TypeError
saying that some positional-only arguments are passed as keyword arguments. So really before this syntax, like we just explored before, there wasn’t really any, a way to define something as a positional-only argument, right?
01:15 Because we did have the same function signature with positional arguments, but we were still always able to call them as keyword arguments as well when actually calling the function. Right.
01:27 So new feature, 3.8 upwards. Now you can actually say this needs to be a positional argument, but you can still have the default values. Right, exactly. You can just call it without any input still, as you did before. Yeah, exactly. I think it just gives you a bit more flexibility or it allows you to customize how you want this function to be called, how you want it to be used.
Become a Member to join the conversation.