Duck Typing using Python
Duck Typing in action
As a QA professional with five years of experience in automation programming using Python, I've come to appreciate the language's flexibility and expressiveness. One of the concepts that stand out in Python is Duck Typing. It's not just a programming principle; it's a philosophy that Python embraces wholeheartedly. In this blog, I'll share some fun tricks and insights into Duck Typing, showing how it can make your Python code more flexible and intuitive.
What is Duck Typing?
Duck Typing is a concept derived from the saying, "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck." In Python, this means that you don't check the type of an object; you check for the presence of a specific method or attribute.
Why is Duck Typing Fun?
- Flexibility: Duck Typing allows for more generic and flexible code. You can write functions that accept any object, as long as it has the methods or attributes you need.
- Simplicity: It simplifies the code. You don?t have to write complex type-checking code.
- Surprise Factor: It's always fun to see an object work seamlessly in a place where you wouldn't traditionally expect it to.
Duck typing is a concept in Python that allows you to use objects without knowing their specific type. This can be helpful when you're working with objects from different libraries or third-party code. For example, you could use the len() function to get the length of a list, a string, or even a tuple:
print(len([1, 2, 3])) print(len("Hello, world!")) print(len((1, 2, 3)))
All of these statements will work because the len() function doesn't care about the specific type of object it's given. It only cares that the object has a __len__() method defined.