Tackling Type Hints
00:00 So far, you’ll learn that duck typing is a common and flexible type system in Python, using built-in types, the standard library, and even third-party code.
00:10 But sometimes it can be challenging to combine duck typing and type hints, which is Python’s way of providing type context. It’s absolutely great that a function can handle different objects as long as they support the right behavior, but sometimes clearly expressing this with type hints can be challenging.
00:28 Next, you’ll explore ways to tackle this issue.
00:32
Type hints are the Pythonic way to show what types of objects a function expects and returns. Here’s a straightforward function called greet
.
00:42
It gets a string as an input and returns a string as an output. This colon str
and the arrow str
is type hinting.
00:54 What are its benefits? Preventing type-related bugs by catching mistakes early, like passing a string when a number is expected. Powering automatic type checkers to spot errors before the code runs. They usually flag the specific lines of your script that have a problem with their type.
01:14 Supporting auto-completion in code editors by suggesting valid methods for a given type, providing code documentation by making it clear what types a function works with, also allowing data validation by making sure a function gets the right kind of input.
01:31 And finally, allowing data serialization by keeping data formats consistent when converting to JSON or other formats.
01:43 Now, what’s this challenge of combining duck typing and type hints? Type hints create challenges by not clearly expressing expected behaviors when using duck typing, making it harder to signal required methods or attributes.
01:58 Let’s see an actual example.
02:01
You have a mean()
function that calculates the average of a list of numbers. It takes grades
as an argument, which is type hinted as a list, meaning it expects to receive a list.
02:12
It then sums the numbers and divides by their count, returning the result as a float. But here’s a catch. The type hint for the grades
argument is limited to list objects and collides head-on with duck typing.
02:27 Because this function actually works with tuples of numbers as well, it can even work with set objects.
02:34 So if I run this code by passing in a list and then a tuple, I get results. But here the type checker is throwing an error that says tuple has an incompatible type.
02:51 How can you make this right? What’s the solution? You actually already learned about one of them. Keep watching.
Become a Member to join the conversation.