Duck Typing in Python: Writing Flexible and Decoupled Code

Duck Typing in Python: Writing Flexible and Decoupled Code
blow post content copied from  Real Python
click here to view original post

Python makes extensive use of a type system known as duck typing. The system is based on objects’ behaviors and interfaces. Many built-in classes and tools support this type system, which makes them pretty flexible and decoupled.

Duck typing is a core concept in Python. Learning about the topic will help you understand how the language works and, more importantly, how to use this approach in your own code.

In this tutorial, you’ll learn:

  • What duck typing is and what its pros and cons are
  • How Python’s classes and tools take advantage of duck typing
  • How special methods and protocols support duck typing
  • What alternatives to duck typing you’ll have in Python

To get the most out of this tutorial, you should be familiar with several Python concepts, including object-oriented programming, classes, special methods, inheritance, and interfaces.

Getting to Know Duck Typing in Python

In object-oriented programming, classes mainly aim to encapsulate data and behaviors. Following this idea, you can replace any object with another if the replacement provides the same behaviors. This is true even if the implementation of the underlying behavior is radically different.

The code that uses the behaviors will work no matter what object provides it. This principle is the basis of a type system known as duck typing.

Duck Typing: Behaving Like a Duck

You’ll find many different definitions of duck typing out there. At its core, this coding style is based on a well-known saying:

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

Extrapolating this to programming, you can have objects that quack like a duck and walk like a duck rather than asking whether those objects are ducks. In this context, quack and walk represent specific behaviors, which are part of the objects’ public interface (API).

Duck typing is a type system where an object is considered compatible with a given type if it has all the methods and attributes that the type requires. This type system supports the ability to use objects of independent and decoupled classes in a specific context as long as they adhere to some common interface.

Duck typing is pretty popular in Python. The language documentation defines duck typing as shown below:

A programming style which does not look at an object’s type to determine if it has the right interface; instead, the method or attribute is simply called or used (“If it looks like a duck and quacks like a duck, it must be a duck.”) By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution.

Duck-typing avoids tests using type() or isinstance(). (Note, however, that duck-typing can be complemented with abstract base classes.) Instead, it typically employs hasattr() tests or EAFP programming. (Source)

Here’s a quick example that involves birds that can swim and fly:

class Duck:
    def swim(self):
        print("The duck is swimming")

    def fly(self):
        print("The duck is flying")

class Swan:
    def swim(self):
        print("The swan is swimming")

    def fly(self):
        print("The swan is flying")

class Albatross:
    def swim(self):
        print("The albatross is swimming")

    def fly(self):
        print("The albatross is flying")

In this example, your three birds can swim and fly. However, they’re completely independent classes. Because they share the same interface, you can use them in a flexible manner:

>>> from birds_v1 import Duck, Swan, Albatross

>>> birds = [Duck(), Swan(), Albatross()]

>>> for bird in birds:
...     bird.swim()
The duck is flying
The duck is swimming
The swan is flying
The swan is swimming
The albatross is flying
The albatross is swimming

Python doesn’t care about what object bird is holding at a given time. It just calls the expected methods. If the object provides the method, then the code works without breaking. That’s the flexibility that duck typing offers.

The duck typing system is pretty popular in Python. In most cases, you shouldn’t worry about making sure that an object is of the right type for using it in a certain piece of code. Instead, you can rely on objects that quack like ducks and walk like ducks.

Duck Typing and Polymorphism

In object-oriented programming, polymorphism allows you to treat objects of different types as the same general type. Polymorphism aims to enable code to work with objects of various types through a uniform interface (API), which helps you write more general and reusable code.

You’ll find different forms of polymorphism in object-oriented programming. Duck typing is one of them.

Read the full article at »

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

February 26, 2024 at 07:30PM
Click here for more details...

The original post is available in Real Python by
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.