Duck Typing in Python — 3 Practical Examples
Let’s learn to use duck typing in Python
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?
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
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…