Duck Typing

In Python, duck typing is a type system where an object is considered compatible with a given type if it has all the methods and attributes that the type requires. This means that you can use an object in your code as long as it has the necessary methods and properties, regardless of its specific type.

The term comes from the well-known saying:

“If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.”

Duck typing is a cornerstone of Python’s dynamic nature. It allows you to write functions and methods that can operate on a wide variety of objects, as long as those objects implement the expected interface. This can lead to cleaner, more maintainable code, as you’re focusing on the capabilities of the objects rather than their specific class or data type.

Example

Here’s a simple example to illustrate duck typing in Python:

Python birds.py
class Duck:
    def swim(self):
        print("The duck is swimming")

    def fly(self):
        print("The duck is flying")

class Swan:
    def swim(self):
        print("The swan is swimming")

    def fly(self):
        print("The swan is flying")

class Albatross:
    def swim(self):
        print("The albatross is swimming")

    def fly(self):
        print("The albatross is flying")

# Usage
birds = [Duck(), Swan(), Albatross()]

for bird in birds:
    bird.fly()
    bird.swim()

# Output:
# The duck is flying
# The duck is swimming
# The swan is flying
# The swan is swimming
# The albatross is flying
# The albatross is swimming

In this example, Duck, Swan and Albatross have .swim() and fly methods. Then you create instances of the three classes and call their methods in a loop without caring about the object type.

Tutorial

Duck Typing in Python: Writing Flexible and Decoupled Code

In this tutorial, you'll learn about duck typing in Python. It's a typing system based on objects' behaviors rather than on inheritance. By taking advantage of duck typing, you can create flexible and decoupled sets of Python classes that you can use together or individually.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Dec. 19, 2024 • Reviewed by Dan Bader