Understanding Duck Typing in Python

Duck typing in Python is a term used to illustrate that code will execute an action based on the types of built-in objects being processed. Here’s what to know.  

Published on Jul. 08, 2024
ducks on a pond representing duck typing in python
Image: Shutterstock / Built In
Brand Studio Logo

Duck typing is a term commonly related to dynamically typed programming languages and polymorphism. The idea behind this principle is that the code itself doesn’t care about whether an object is a duck, rather it only cares about whether it quacks.

Python Duck Typing Explained

Duck typing is a principle used in dynamically typed programming languages like Python in which the code isn’t constrained or bound to specific data types. Instead, it will execute an action depending on the type of built-in objects being processed. 

If it walks like a duck, and it quacks like a duck, then it must be a duck.

More on PythonHow to Write Pythonic Code

 

What Is Duck Typing in Python?

Let’s consider the + Python operator. If we use it with two integers, then the result will be the sum of the two numbers.

>>> a = 10 + 15
>>> a
25

Now, let’s consider the same operator with string object types. The result will be the concatenation of the two objects being added together.

>>> a = 'A' + 'B'
>>> a
'AB'

This polymorphic behavior is the core idea behind Python, which is also a dynamically typed language. This means that it performs type checking at run-time, as opposed to statically typed languages, such as Java, that perform it during compile-time.

Additionally, in statically typed languages, we must also declare the data type of the variable prior to its reference in the source code.

// Python
a = 1
// Java
int a;
a = 1

Python itself automatically overloads some operators, such that they perform different actions depending on the type of built-in objects being processed.

def add_two(a, b):
    print(a + b)

This means that any object that supports the + operator will work. In fact, the language itself overloads some operators so that the action taken is dependent to the specific data types of the objects being involved.

Duck typing refers to the principle of not constraining or binding the code to specific data types.

A tutorial on duck typing in Python. | Video: Telusko

More on PythonWhat Does “If__name__==’__main__’” Do in Python?

 

Python Duck Typing Examples

Let’s consider the two example classes below.

class Duck: 
    
    def __init__(self, name):
        self.name = name
    def quack(self):
        print('Quack!')
class Car: 
  
    def __init__(self, model):
        self.model = model
    
    def quack(self):
        print('I can quack, too!')

Since Python is a dynamically typed language, we don’t have to specify the data type of the input arguments in a function.

def quacks(obj):
    obj.quack()

Now, if we call the same function twice with a different object, the action taken will be dependent to the data type of the input object.

>>> donald = Duck('Donald Duck')
>>> car = Car('Tesla')
>>>
>>> quacks(donald)
'Quack!'
>>>
>>> quacks(car)
'I can quack, too!'

If the object does not support a specified operation it will automatically raise an exception.

>>> a = 10
>>> quacks(a)
AttributeError: 'int' object has no attribute 'quack'

In Python, we’d usually avoid enforcing such manual error checking, as it would limit the types of objects that can be involved. In some special cases you may still want to check the type of an object, such as using type() built-in function.

However, you should avoid differentiating the action taken based on the specific data types as this will reduce the flexibility of the code. In other occasions though, this may indicate a problem at the design level rather than the code itself.

That’s everything you need to know about duck typing and how it relates to the concepts of polymorphism and method overloading. Additionally, we’ve covered the main differences between statically and dynamically typed languages and how this enables Python code to be applied to objects without caring about their actual data types.

Frequently Asked Questions

Duck typing is a term used to describe the polymorphic behavior of objects in dynamically typed programming languages like Python. This principle allows an action to be taken depending on the type of built-in objects being processed. It doesn’t care that an object is a duck, it only cares about whether it quacks.

In one example of duck typing in Python, the + operator can be used to add two integers together. However, the same operator can also be used with string object types. Python will be able to differentiate between the two situations and produce a sum for the two integers, and separately, a concatenation of the two string object types. 

Explore Job Matches.