Duck, Duck, Code: An Introduction to Python’s Duck Typing


Python's Duck Typing
Picture by Creator | DALLE-3 & Canva

 

 

What’s Duck Typing?

 

Duck typing is an idea in programming typically associated to dynamic languages like Python, that emphasizes extra on the thing’s conduct over its kind or class. Once you use duck typing, you test whether or not an object has sure strategies or attributes, quite than checking for the precise class. The title comes from the saying,

 

If it appears to be like like a duck, swims like a duck, and quacks like a duck, then it in all probability is a duck.

 

Duck typing brings a number of benefits to programming in Python. It permits for extra versatile and reusable code and helps polymorphism, enabling totally different object sorts for use interchangeably so long as they supply the required interface. This ends in less complicated and extra concise code. Nevertheless, duck typing additionally has its disadvantages. One main disadvantage is the potential for runtime errors. Moreover, it will possibly make your code difficult to grasp.

 

Understanding Dynamic Conduct in Python

 

In dynamically typed languages, variable sorts usually are not mounted. As an alternative, they’re decided at runtime based mostly on the assigned values. In distinction, statically typed languages test variable sorts at compile time. As an example, in case you try and reassign a variable to a price of a distinct kind in static typing, you’ll encounter an error. Dynamic typing supplies larger flexibility in how variables and objects are used.

Let’s take into account the * Python operator; it behaves otherwise based mostly on the kind of the thing it’s used with. When used between two integers, it performs multiplication.

# Multiplying two integers
a = 5 * 3
print(a)  # Outputs: 15

 

When used with a string and an integer, it repeats the string. This demonstrates Python’s dynamic typing system and adaptable nature.

# Repeating a string
a="A" * 3
print(a)  # Outputs: AAA

 

 

How Duck Typing Works in Python?

 

Duck typing is most popular in dynamic languages as a result of it encourages a extra pure coding type. Builders can concentrate on designing interfaces based mostly on what objects can do. In duck typing, strategies outlined inside the category are given extra significance than the thing itself. Let’s make clear this with a primary instance.

 

Instance No: 01

We’ve got two courses: Duck and Particular person. Geese could make a quack sound, whereas individuals can converse. Every class has a technique known as sound that prints their respective sounds. The perform make_it_sound takes any object that has a sound methodology and calls it.

class Duck:
    def sound(self):
        print("Quack!")

class Particular person:
    def sound(self):
        print("I am quacking like a duck!")

def make_it_sound(obj):
    obj.sound()

 

Now, let’s have a look at how we will use duck typing to work for this instance.

# Utilizing the Duck class
d = Duck()
make_it_sound(d)  # Output: Quack!

# Utilizing the Particular person class
p = Particular person()
make_it_sound(p)  # Output: I am quacking like a duck!

 

On this instance, each Duck and Particular person courses have a sound methodology. It does not matter if the thing is a Duck or a Particular person; so long as it has a sound methodology, the make_it_sound perform will work accurately.

Nevertheless, duck typing can result in runtime errors. As an example, altering the title of the tactic sound within the class Particular person to talk will increase an AttributeError on runtime. It is because the perform make_it_sound expects all of the objects to have a sound perform.

class Duck:
    def sound(self):
        print("Quack!")

class Particular person:
    def converse(self):
        print("I am quacking like a duck!")

def make_it_sound(obj):
    obj.sound()

# Utilizing the Duck class
d = Duck()
make_it_sound(d)

# Utilizing the Particular person class
p = Particular person()
make_it_sound(p)

 

Output:

AttributeError: 'Particular person' object has no attribute 'sound'

 

Instance No: 02

Let’s discover one other program that offers with calculating areas of various shapes with out worrying about their particular sorts. Every form (Rectangle, Circle, Triangle) has its personal class with a technique known as space to calculate its space.

class Rectangle:
    def __init__(self, width, peak):
        self.width = width
        self.peak = peak
        self.title = "Rectangle"

    def space(self):
        return self.width * self.peak

class Circle:
    def __init__(self, radius):
        self.radius = radius
        self.title = "Circle"

    def space(self):
        return 3.14 * self.radius * self.radius

    def circumference(self):
        return 2 * 3.14 * self.radius

class Triangle:
    def __init__(self, base, peak):
        self.base = base
        self.peak = peak
        self.title = "Triangle"

    def space(self):
        return 0.5 * self.base * self.peak

def print_areas(shapes):
    for form in shapes:
        print(f"Space of {form.title}: {form.space()}")
        if hasattr(form, 'circumference'):
            print(f"Circumference of the {form.title}: {form.circumference()}")

# Utilization
shapes = [
    Rectangle(4, 5),
    Circle(3),
    Triangle(6, 8)
]

print("Areas of various shapes:")
print_areas(shapes)

 

Output:

Areas of various shapes:
Space of Rectangle: 20
Space of Circle: 28.259999999999998
Circumference of the Circle: 18.84
Space of Triangle: 24.0

 

Within the above instance, we have now a print_areas perform that takes a listing of shapes and prints their names together with their calculated areas. Discover that we need not test the kind of every form explicitly earlier than calculating its space. As the tactic circumference is simply current for the Circle class, it will get carried out solely as soon as. This instance exhibits how duck typing can be utilized to write down versatile code.

 

Last Ideas

 

Duck typing is a strong function of Python that makes your code extra dynamic and versatile, enabling you to write down extra generic and adaptable packages. Whereas it brings many advantages, similar to flexibility and ease, it additionally requires cautious documentation and testing to keep away from potential errors.

 
 

Kanwal Mehreen Kanwal is a machine studying engineer and a technical author with a profound ardour for information science and the intersection of AI with medication. She co-authored the e book “Maximizing Productiveness with ChatGPT”. As a Google Technology Scholar 2022 for APAC, she champions variety and educational excellence. She’s additionally acknowledged as a Teradata Range in Tech Scholar, Mitacs Globalink Analysis Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having based FEMCodes to empower girls in STEM fields.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *