Picture by Writer | 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 habits over its kind or class. Once you use duck typing, you test whether or not an object has sure strategies or attributes, somewhat 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 most likely 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 leads to less complicated and extra concise code. Nonetheless, duck typing additionally has its disadvantages. One main disadvantage is the potential for runtime errors. Moreover, it will probably make your code difficult to grasp.
Understanding Dynamic Habits in Python
In dynamically typed languages, variable sorts should not fastened. As a substitute, they’re decided at runtime based mostly on the assigned values. In distinction, statically typed languages test variable sorts at compile time. As an illustration, for those who try and reassign a variable to a worth of a special kind in static typing, you’ll encounter an error. Dynamic typing gives higher flexibility in how variables and objects are used.
Let’s contemplate the *
Python operator; it behaves in another way 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 model. Builders can deal with 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
Now we have two courses: Duck and Particular person. Geese could make a quack sound, whereas folks can communicate. Every class has a way referred to 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.
Nonetheless, duck typing can result in runtime errors. As an illustration, altering the title of the tactic sound
within the class Particular person to talk will elevate 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 communicate(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 way referred to as space to calculate its space.
class Rectangle:
def __init__(self, width, top):
self.width = width
self.top = top
self.title = "Rectangle"
def space(self):
return self.width * self.top
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, top):
self.base = base
self.top = top
self.title = "Triangle"
def space(self):
return 0.5 * self.base * self.top
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 now have a print_areas
perform that takes a listing of shapes and prints their names together with their calculated areas. Discover that we needn’t test the kind of every form explicitly earlier than calculating its space. As the tactic circumference
is just current for the Circle
class, it will get carried out solely as soon as. This instance reveals how duck typing can be utilized to jot down versatile code.
Last Ideas
Duck typing is a robust characteristic of Python that makes your code extra dynamic and versatile, enabling you to jot down extra generic and adaptable applications. Whereas it brings many advantages, akin 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 knowledge science and the intersection of AI with drugs. She co-authored the book “Maximizing Productiveness with ChatGPT”. As a Google Technology Scholar 2022 for APAC, she champions range and tutorial excellence. She’s additionally acknowledged as a Teradata Variety in Tech Scholar, Mitacs Globalink Analysis Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having based FEMCodes to empower ladies in STEM fields.