![duck typing duck typing](https://i.ytimg.com/vi/xLrMvb4H1bI/maxresdefault.jpg)
The second time it added two floating point numbers. The first time the function was called, it was given two integers, and it added them together and printed out a result line. This seems pretty good, except perhaps for that last one. Let’s try it on some different inputs, in the Python REPL: Since Python is a dynamically-typed object-oriented language, these two arguments can be any two objects. This function doesn’t look like much, and it isn’t, but duck typing makes it work on a huge variety of inputs, now and in the future. Here’s a simple Python example to illustrate the immense powers of duck typing: JavaScript’s duck typing implementation is a bit less powerful, but it’s still useful.
![duck typing duck typing](https://slidetodoc.com/presentation_image_h/2d9390f6d7d41c8851fae028d859ca2f/image-12.jpg)
Duck typing is my absolute favorite feature of Python, especially when combined with dunder methods (dunder is short for “double underscore”, which is their method naming convention), also known as magic methods.
Duck typing code#
In simple terms, if the passed-in object has a quack() method like a duck does, then it will be treated like a duck.Īs long as you don’t lock down your Python or JavaScript code by enforcing static type checking, duck typing can deliver tremendous benefits by helping to futureproof your code.
![duck typing duck typing](https://iq.opengenus.org/content/images/2019/09/1-1.png)
As long as the named method exists inside the object, it will be invoked and the code should work. Duck typing is the ability to write code that can execute a named method on any object from any class that is passed to the code. The second in a series of posts highlighting the commonalities of Python and JavaScript.Īs dynamically typed languages, both Python and JavaScript support duck typing. Tl dr: Life is easier if you can treat any object like a duck if it quacks like a duck. Python and JavaScript: the joys of duck typing