WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Advanced · question 52 of 100

What is the principle of duck typing in Python, and how does it affect the way you write code?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

Duck typing is a concept in Python that refers to the practice of determining an object’s type based on its behavior rather than its class or type. The name "duck typing" comes 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 if an object can perform a certain set of operations, it is considered to be of a certain type, regardless of its class or type. This allows for greater flexibility and dynamic behavior in Python code.

For example, let’s say we have a function that accepts an object and performs some operation on it. With duck typing, we don’t care what class or type the object is, as long as it has the required attributes or methods:

    def perform_operation(obj):
        obj.do_something()
        obj.do_something_else()

In this example, we don’t care what class or type obj is, as long as it has the do_something() and do_something_else() methods.

One advantage of duck typing is that it allows for greater code reusability. Instead of requiring that an object be of a specific class or type, we can write functions that can work with any object that has the required behavior.

However, one downside of duck typing is that it can lead to runtime errors if an object doesn’t have the required behavior. This can be mitigated by using type annotations and static analysis tools to catch potential issues before runtime.

In summary, duck typing is a powerful concept in Python that allows for greater flexibility and code reusability. It’s important to be aware of the potential downsides and to use type annotations and static analysis tools to catch potential issues.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics