Skip to content

Duck Typing: How to Effortlessly Use and Fix in Python

[

Duck Typing in Python

In this tutorial, we’ll explore the concept of duck typing in Python. Duck typing is related to dynamic typing, where the type or class of an object is less important than the methods it defines. Instead of checking for specific types, duck typing allows you to check for the presence of particular methods or attributes in an object.

What is Duck Typing?

The term “duck typing” comes from the saying, “If it walks like a duck and it quacks like a duck, then it must be a duck.” This concept emphasizes that as long as an object behaves like a particular type by implementing the required methods, it can be considered an instance of that type.

To demonstrate duck typing, let’s consider the built-in len() function in Python. The len() function can be called on any object that defines a .__len__() method.

class TheHobbit:
def __len__(self):
return 95022
the_hobbit = TheHobbit()
print(len(the_hobbit)) # Output: 95022

In this example, we define a class TheHobbit with a .__len__() method that returns the word count of the book “The Hobbit”. We then create an instance of TheHobbit called the_hobbit and call the len() function on it, which returns the length value of 95022.

Similarly, we can call the len() function on other objects that define the .__len__() method:

my_str = "Hello World"
my_list = [34, 54, 65, 78]
my_dict = {"one": 123, "two": 456, "three": 789}
print(len(my_str)) # Output: 11
print(len(my_list)) # Output: 4
print(len(my_dict)) # Output: 3

In the above example, we call len() on a string, a list, and a dictionary, and obtain the respective lengths.

However, if we try to call len() on an object that does not define the .__len__() method, we’ll get a TypeError:

my_int = 7
my_float = 42.3
print(len(my_int)) # Raises TypeError: object of type 'int' has no len()
print(len(my_float)) # Raises TypeError: object of type 'float' has no len()

Here, since integers and floats do not have a .__len__() method defined, attempting to call len() on them raises an exception.

In summary, when using duck typing, the only requirement for calling len(obj) is that the object must define a .__len__() method. The actual type of the object can vary, including built-in types like strings, lists, dictionaries, or custom-defined classes like TheHobbit.

Conclusion

Duck typing allows you to focus on the behavior and capabilities of an object rather than its specific type. By checking for the presence of methods or attributes, you can determine if an object is suitable for a particular operation or function call.

In the next tutorial, we’ll dive into type hinting in Python, which allows you to annotate the types of variables and function parameters for better code readability and maintainability.

Related Articles: