Rock Solid Python with Python Typing Transcripts
Chapter: Static vs. Dynamic Languages
Lecture: Duck Typing

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Before we move on from our untyped example, let's talk about duck typing. We saw that in Wikipedia, Python has duck typing, but also strong typing.
0:12 Typically those don't go together, although we'll see there's some interesting ways in
0:15 the orthogonal typing section that we're going to talk about near the end of the course that they kind of do.
0:21 But in general, we have two types of typing. We have strong typing or strict, and then we have duck typing, which is just kind of how you use it.
0:30 like a duck quacks like a duck. It is a duck. Let's see how that works in our example here.
0:36 So right now we've got our class and it takes a model and it takes a style and an engine
0:43 size but what are these right? This is an integer is this a float is that a Boolean
0:47 is that a yes no, we don't know. Partial like it's somewhat off road. It's not a great off
0:54 road bike but it does technically support it. So we don't have a lot of information Let's go ahead and just use our bike here for a minute.
1:02 We're going to print out a little bit of extra information. We'll say the B.model can, and we're going to say can or cannot jump, depending on how,
1:14 whether or not it can jump. So we'll come in here and we'll say, in this case, just nothing if it can jump. So we'll say if B.canJump.
1:24 jump, else we'll put here not and jump. Let's go ahead and run this real quick, see what we get.
1:34 You can see the Tenere can jump with extra spacing, always fun there. All right, the Tenere can jump, somewhat.
1:42 Over here we were saying that whatever a motorcycle is, it has a model and it can jump.
1:49 the can jump is truthy, not yes or no, because those are both pass as true strings, but it's
1:55 a Boolean like thing. So in the type specification, the duck type means a string model and a truthy
2:09 can jump field property, it doesn't really know what our cycles are also spelled right.
2:15 we go. So this is the duck typing, right? If what do you really need? Does it technically
2:21 need to be a motorcycle to run this code? When it comes back from crate bikes? No, it
2:26 just needs a list of things or technically iterable of things doesn't have to be a list
2:31 could be a tuple. But the things in there have to have a mo a model in a can jump. So
2:37 when we say you have duck typing, it's just like, well, that's how you use it. And it then it must be one of those things, right?
2:45 If I can use it like a motorcycle, it must be a motorcycle, even if the type information says it's not really. So this is an important idea.
2:53 This is how Python, the only way Python worked before, with 3.5, before 3.5, and when they added the typing, explicit type hints to the language.


Talk Python's Mastodon Michael Kennedy's Mastodon