💻 Programming

Duck Typing

Duck Typing

"If it walks like a duck and quacks like a duck, it's a duck" - dynamic typing that judges an object by its methods and attributes rather than its type.

📖 Detailed Explanation

Duck Typing is a programming concept that originates from the maxim "If it walks like a duck and quacks like a duck, it's a duck." It judges suitability not by an object's actual type but by which methods and attributes the object has.

In statically typed languages (Java, C++), types are defined through explicit interfaces or inheritance, but in languages that support duck typing (Python, JavaScript, Ruby), any object can be used as long as it implements the required methods. This greatly increases flexibility, but it also carries the risk of runtime errors.

In Python, duck typing is a core philosophy. A `for` statement can iterate over any object that has an `__iter__` method, and the `len()` function works on any object that implements `__len__`. This kind of "protocol"-based approach makes it possible to implement polymorphism without inheritance.

TypeScript's Structural Typing can be seen as the statically typed version of duck typing. Even without explicitly implementing an interface, a type is accepted as that type if it has the required properties and methods. This contrasts with Java's Nominal Typing.

💻 Code Example

# Python에서의 덕 타이핑 예제
class Duck:
    def walk(self):
        return "뒤뚱뒤뚱"

    def quack(self):
        return "꽥꽥!"

class Person:
    def walk(self):
        return "걷는다"

    def quack(self):
        return "꽥꽥 흉내"

class Robot:
    def walk(self):
        return "삐빅 이동"

    def quack(self):
        return "QUACK 출력"

# 덕 타이핑: 타입이 아닌 메서드 존재 여부로 판단
def make_it_quack(duck_like):
    """walk와 quack 메서드만 있으면 어떤 객체든 OK"""
    print(f"걷기: {duck_like.walk()}")
    print(f"울음: {duck_like.quack()}")

# 모두 작동! 타입 상속 없이도 다형성 구현
for obj in [Duck(), Person(), Robot()]:
    make_it_quack(obj)
    print("---")

# 프로토콜 기반 덕 타이핑 (Python 표준)
class FilelikeObject:
    """read() 메서드만 있으면 파일처럼 사용 가능"""
    def __init__(self, data):
        self.data = data
        self.position = 0

    def read(self, size=-1):
        if size == -1:
            result = self.data[self.position:]
            self.position = len(self.data)
        else:
            result = self.data[self.position:self.position + size]
            self.position += size
        return result

# 실제 파일이 아니어도 read()가 있으면 동작
import json
fake_file = FilelikeObject('{"name": "duck", "type": "bird"}')
data = json.load(fake_file)  # 파일처럼 사용됨
print(data)  # {'name': 'duck', 'type': 'bird'}

🗣️ Examples of Practical Conversations

In a Python code review

"This function doesn't need to accept only lists. It only needs `__iter__`, so if you change the type hint to `Iterable[str]`, it can also accept generators and tuples. If you take advantage of duck typing, you get a more flexible API."

During a TypeScript migration discussion

"Thanks to TypeScript's structural typing, you can migrate existing JavaScript code incrementally. Even if you don't declare an interface with implements, type checking passes as long as the structure matches, so compatibility with legacy code is good."

While writing test code

"Duck typing is convenient when creating mock objects. Instead of inheriting the whole class, you just create an object that has only the methods needed for the test. Python's MagicMock makes good use of this."

📊 Comparison of Typing Approaches

Method Language Features When Checked
Duck Typing Python, Ruby, JS Judged by whether the method exists Runtime
Structural Typing TypeScript, Go Compatibility judged by structure (shape) Compile time
Nominal Typing Java, C#, C++ Explicit inheritance/implementation required Compile time

💡 Practical tip: If you need type safety in Python, use Protocol (PEP 544). You can get both the flexibility of runtime duck typing and the safety of static type checking.

⚠️ Cautions

1
Risk of Runtime Errors

Duck typing cannot catch type errors at compile time. If you pass an object that lacks a required method, an AttributeError occurs only at runtime. For critical code, use type hints together with runtime checks.

2
Documenting Implicit Interfaces

With duck typing, it is easy for "which methods are required" to become implicit. Document the expected interface clearly with Protocol type hints or docstrings. Otherwise, maintenance becomes difficult.

3
Method Name Collisions

Methods with the same name can be used with different meanings. Depending on the context, `close()` may mean closing a file, closing a UI window, or terminating a connection. You must also consider semantic compatibility.

🔗 Related Terms

📚 Learn More