DEV Community


Posted on

Duck typing in Python

Duck typing is a concept in programming languages, including Python, where the type or class of an object is determined by its behavior (methods and properties) rather than its explicit class or type declaration. In duck typing, "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck."

In other words, duck typing focuses on what an object can do, rather than what it is. If an object can perform certain actions or has certain attributes, it's treated as if it belongs to a certain type or class, even if it doesn't explicitly inherit from that type or class.


class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

class Duck:
    def speak(self):
        return "Quack!"

def animal_sound(animal):
    return animal.speak()

dog = Dog()
cat = Cat()
duck = Duck()

print(animal_sound(dog))  # Output: Woof!
print(animal_sound(cat))  # Output: Meow!
print(animal_sound(duck)) # Output: Quack!
Enter fullscreen mode Exit fullscreen mode

In this example, the animal_sound function takes an argument that is expected to have a speak method. Duck typing allows us to pass objects of different classes (Dog, Cat, and Duck) to the function, as long as they have a compatible method (speak). The function doesn't care about the actual type of the object; it only relies on the presence of the required method.

Real-Life Example:

Imagine you're building a music player application. You might have different classes for different audio file types, like MP3, WAV, and FLAC. Instead of checking the specific class type for each audio file, you can use duck typing to determine whether an audio file can be played:

class MP3:
    def play(self):
        print("Playing MP3 audio")

class WAV:
    def play(self):
        print("Playing WAV audio")

class FLAC:
    def play(self):
        print("Playing FLAC audio")

def play_audio(audio):

mp3 = MP3()
wav = WAV()
flac = FLAC()

play_audio(mp3)  # Output: Playing MP3 audio
play_audio(wav)  # Output: Playing WAV audio
play_audio(flac) # Output: Playing FLAC audio
Enter fullscreen mode Exit fullscreen mode

In this example, the play_audio function expects an object with a play method. As long as an object has this method, it can be treated as an audio file and played using the function.

Duck typing simplifies code and promotes flexibility by allowing you to work with different classes and types that exhibit similar behavior. It's a powerful concept in dynamic programming languages like Python, making the code more concise and adaptable.

Top comments (0)