Write Pythonic Code Like a Seasoned Developer Transcripts
Chapter: Methods and Functions
Lecture: Variable argument counts for overloads

Login or purchase this course to watch this video and the rest of the course contents.
0:01 Another way to add flexibility to functions is to allow you to pass a variable number or maybe more correctly an arbitrary number of parameters to it.
0:11 So let's look at that in this case of the silly function I wrote called biggest, so "biggest" will take two numbers,
0:17 any really two comparables and tell you which one is bigger, so like biggest of 1 and 7, surprise, it's 7. Let's go look at this in code.
0:25 Here we have the same thing as on our slides, if we run this, you can see still 7 is bigger than 1, hasn't changed.
0:32 Cool, but what if we want to have more than 1 argument, what if we wanted to somehow, let's go in and write the code
0:40 what if we wanted to say the biggest of 1 and 7 and 42 and 99 and -1 and 11; what if I wanted to write that code?
0:49 Well, if I try it's obviously not going to love it because it says it took two positional parameters I was given 6,
0:55 not a good deal, so we can use convention here in Python called *args,
1:01 so star, args is the convention, * (star) is the keyword or the language feature,
1:07 that says this thing is going to accept an arbitrary number of parameters,
1:11 the x means first it means you have to supply at least one but you may supply more,
1:15 so let's first of all just print out what is this args and what is it and let's comment that out for a moment,
1:23 if I try this again, you can see that I was given a tuple 7, 42 and so on, if we look here, that's the remainder after the x.
1:32 So let's go write the code that actually does the biggest part here, there, that seems like a reasonable implementation,
1:42 we'll start out assuming the one that we have is the biggest and we'll go through everything that was passed to us as many arguments,
1:48 zero or more that you give us and we'll check, well is this one bigger, if it is we'll set that one to be the result.
1:53 So what should the answer be at the end? 99 of course. Boom, and it is. So here is another Pythonic way to add flexibility to your methods,
2:03 in a graphic, we saw we had this limited version that could compare two things, using *args
2:10 we were able to upgrade it to take an arbitrary number of items and we saw that the thing that's passed in the args
2:16 is actually a tuple and we just loop over it or do whatever you want to do with the tuple of additional parameters.


Talk Python's Mastodon Michael Kennedy's Mastodon