Introduction to Duck Typing
In many programming languages like Java or C++, you must tell the computer what type (like integer, string, or class) your object is before you can use it. Python is different. It uses something called dynamic typing, which means it only checks the type of an object when the program is running, not before.
Duck typing goes one step further. It does not care about the exact type of the object at all. Instead, it only checks whether the object can perform the required actions. This is explained with the famous phrase:
"If it looks like a duck, swims like a duck, and quacks like a duck, then it must be a duck."
In programming, this means: if an object has the methods and attributes that are expected, it does not matter what type or class the object really belongs to.
This way, tools like IDEs and linters can warn you if the wrong type of object is passed.
📌 Summary
Duck typing in Python focuses on what an object can do instead of what it is. This makes Python code flexible, simple, and powerful. Objects of different types can be used in the same way if they share the same behavior. However, since Python does not strictly enforce types, you need to be careful with testing and readability. By combining duck typing with type hints and good practices, you can write code that is both flexible and easy to understand.