Duck Typing in Python — 3 Practical Examples
Let’s learn to use duck typing in Python
--
Duck Typing
Duck typing shouldn’t be an unfamiliar concept to seasoned programmers. For new learners, it may sound to be an interesting phrase. What do ducks have anything to do with programming?
From a retrospective perspective, this concept is adapted from the following expression as a form of abductive reasoning, as you can find on Wikipedia.
If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.
We don’t need to relate this expression to programming for now, but we should’ve already noticed that this expression pertains to how we can identify a duck. In essence, we don’t need to have a genomic sequencing of the animal of interest to know its identity. Instead of approaching the internal factors, we draw our conclusion based on its external appearance and behaviours.
If I encounter a duck-like bird that swims and quacks just like a duck in real life, I will call it a duck, so will my 8-year-old daughter. There’s no rocket science, but just simple life experience that leads to the possibly best-educated guess.
All kidding aside, what’s the relevance of duck typing to programming, particularly to Python — the language of interest for the present article?
Dynamic vs. Static Typing
The concept of duck typing has been mostly adopted in programming languages that support dynamic typing, such as Python and JavaScript. In these languages, a common feature is that we declare variables without the need to specify their types. Later in the code, if we wish, we can assign other data types to these variables. Some examples in Python are given below.
As you can see from the above code snippet, we initially assigned an integer to the variable a
, making it of the int
type. Later, we assigned a string and a list of numbers to the same…