Duck Typing in Python

💡 Idea: Duck typing is a computer science concept where the type of an object is largely ignored—only the methods the object defines matter. This is sometimes referred to as dynamic typing because the type of an object is determined dynamically at runtime rather than checked by the compiler. Instead of checking the type, the programming language (e.g., Python) simply attempts to run the methods as specified in the code. If it works, great, if not it raises an error.

Duck Typing Defined

This method is used to provide assistance for dynamic typing in Python.

With dynamic typing, you do not need to stipulate the variable data type. 

You are able to use different data type principles to the same variable later in the code. 

For example, in the below code snippet, you assign an int, a list, and a string to variable x.

x = 14

x = [100, 200, 300, 400]

x = 'Duck'

When you run the code, you see the Python interpreter returns the results without an error.  This is a result of dynamic typing. 


[100, 200, 300, 400]

Programming languages such as Java will require you to announce a variable and note its data type.

Duck Typing Example

You see in this sample Duck typing is giving the code a try, and if it comes across an unknown it attempts to solve it anyway. 

In the below code treat it as a duck if it can swim, and has wings if not try something else. 

class Duck:  
    def swim(self):  
        print("I'm a duck, and I can swim.")  
    def Wings(self):  
        print("I'm a duck, and I can fly.")   

class deer:  
    def swim(self):  
        print("I'm a deer, and I can swim, but I can not fly.")  

for animal in [Duck(), Deer()]:

When you run the code, the duck can swim and fly.  The deer can swim but can not fly, and we get an attribute error that the object deer does not have wings.


I'm a duck, and I can swim.
I'm a duck, and I can fly.
I'm a deer, and I can swim, but I can not fly.
Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\", line 13, in <module>
AttributeError: 'deer' object has no attribute 'wings'

Video Duck Typing