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

00:00 Abstract base classes, or ABCs, help bridge the gap between duck typing and type hints by providing structure while still keeping things flexible. They make type hints more useful by clarifying intent and catching mistakes early, while still allowing dynamic Pythonic code.

00:20 You’ve already used ABCs before, so now it is time to figure out how to use them to fix the problem you saw a little while ago.

00:28 Let’s go back to this example of how duck typing can collide with type hints. Just to recap, you have a mean() function that calculates the average of a list of numbers.

00:39 It takes grades as an argument, which is type hinted as a list, meaning it’s expected to receive a list. It then sums the numbers and divides by their count, returning the result as a float.

00:50 But as you saw earlier, because of duck typing, it also works with other iterable types like tuples and even sets.

00:59 How do you type hint this function in a way that actually works and is suitable for duck typing? Think about it. Google it even, and then comment your answer below.

01:11 Ready? A union type expression, introduced with type hints, allows a variable to accept multiple types, and it’s defined using Union from the typing module or with the | operator.

01:27 And here is how you use it. You’re saying the grades object can be a list, a tuple, or even a set. This is consistent with duck typing and just makes more sense. When you look at it, you understand the intent quickly.

01:43 But it’s a bit cumbersome, right? What if you just want a general solution? And by a general solution, it means you need the input object to be an iterable and support the len() built-in function.

01:56 Turns out you can use ABCs for this.

01:59 Python has a very useful class called the Collection abstract base class. It’s from the collections.abc module, which is a built-in way to represent objects that are both iterable and have a length.

02:14 This means anything like lists, tuples, sets, or other custom data structures that support len() and can be looped over. Using Collection as a type hint, let’s go ahead and create an ABC to create a more general solution of the mean() function.

Become a Member to join the conversation.