Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Duck Typing

Give Feedback

In this lesson, you’ll learn about duck typing. This term comes from the saying “If it walks like a duck, and it quacks like a duck, then it must be a duck.” (There are other variations).

Duck typing is a concept related to dynamic typing, where the type or the class of an object is less important than the methods it defines. When you use duck typing, you do not check types at all. Instead, you check for the presence of a given method or attribute.

For example, you can call len() on any Python object that defines a .__len__() method:

>>>
>>> class TheHobbit:
...     def __len__(self):
...         return 95022
...
...
>>> the_hobbit = TheHobbit()

>>> the_hobbit
<__main__.TheHobbit object at 0x108deeef0>

>>> len(the_hobbit)
95022

>>> my_str = "Hello World"
>>> my_list = [34, 54, 65, 78]
>>> my_dict = {"one": 123, "two": 456, "three": 789}

>>> len(my_str)
11
>>> len(my_list)
4
>>> len(my_dict)
3
>>> len(the_hobbit)
95022

>>> my_int = 7
>>> my_float = 42.3

>>> len(my_int)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    len(my_int)
TypeError: object of type 'int' has no len()

>>> len(my_float)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    len(my_float)
TypeError: object of type 'float' has no len()

In order for you to call len(obj), the only real constraint on obj is that it must define a .__len__() method. Otherwise, the object can be of types as different as str, list, dict, or TheHobbit.

Become a Member to join the conversation.