Exploring Alternatives to Duck Typing
00:00 Duck typing is great when objects share common behaviors, but as you saw in one of the previous lessons, sometimes it can lead to unexpected issues and isn’t always the best approach.
00:12 In what scenarios would using duck typing be a bad idea? Let’s look at this example. Say you have a platform with different types of media: on-demand videos, podcasts, and live streams.
00:26
At first glance, they all seem similar because they share methods like play()
, pause()
, and rewind()
. But there’s a problem.
00:34
Live streams in this platform don’t rewind. If you try calling the rewind()
method on a livestream object, Python will let you do it until it crashes, because livestreams usually just don’t support rewinding.
00:48 This is where relying only on duck typing can be risky. Just because different objects have similar methods doesn’t mean they all behave the same way.
00:58 Now it’s your turn. Can you think of other situations where objects seem similar but behave differently and using duck typing might cause trouble? Drop your ideas in the comment section.
01:11 Okay, so that’s the problem. What’s the solution? In cases like this, adding explicit checks or using abstract base classes can help prevent unexpected errors.
01:23 In the next few lessons, you’ll learn more about them.
Become a Member to join the conversation.