Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Combining ABCs And Duck Typing: Code

00:00 So the goal here is to come up with a general solution using ABCs that lets you type hint the mean() function from before in a way that’s also consistent with duck typing.

00:12 First of all, let’s import Collection from collections.abc import Collection.

00:22 Now let’s define the function: def mean(grades ): Collection. So here you’re saying you need your input to be a Collection, meaning you can use a for loop on it and also it needs to support the len() function.

00:41 And you want the output to be a float so -> float:

00:47 and here you’re basically just returning the same thing as before. The sum of grades divided by the length of grades. So return sum(grades) / len(grades) and you’re actually done.

01:06 Let’s save this and give it a try on the terminal.

01:10 First, let’s import the function.

01:15 Now let’s try a set. So print(), these are just some random numbers, 3, 7, and 21. Let’s give it a go, and it works. You get 10.3333. Great, you get results from your function, but you haven’t checked the main thing yet.

01:32 You need to check if your type checker is happy or not. So let’s go back to VS Code and you have a list of numbers and a tuple of numbers. In the previous example, your type checker was really unhappy with the tuple.

01:47 Let’s see if the problem is solved. Right off the bat, you can see that in the problem section there is nothing and everything seems to be working fine.

01:57 To sum up, instead of specifying different types like list, tuple, or set, you used Collection from the collections.abc module, which allowed any input that supports iteration and the len() function.

02:13 This makes the function more flexible and easier to read. And also your type checker won’t get mad at you either.

Become a Member to join the conversation.