I. What Is Duck Typing
Duck Typing is a common way of using types in dynamically typed languages. Its core idea is:
If an object walks like a duck and quacks like a duck, it can be treated as a duck.
This statement emphasizes not what type an object belongs to, but whether the object can provide the behavior required by the current scenario.
In traditional Nominal Typing systems, deciding whether an object can be used in a given scenario usually requires checking whether it declares that it implements a specified interface, inherits from a specified base class, or belongs to a certain type.
In duck typing, by contrast, the focus is on whether the object has the required methods, attributes, and operations.
For example:
class Dog:
def speak(self):
return "汪汪"
class Cat:
def speak(self):
return "喵喵"
class Duck:
def speak(self):
return "嘎嘎"
def make_sound(animal):
print(animal.speak())
make_sound(Dog())
make_sound(Cat())
make_sound(Duck())
The three classes share no common parent class and do not explicitly implement any interface, but all of them provide a speak() method, so all of them can be passed to make_sound().
The function does not care about the object's concrete type; it depends only on whether the object has the speak() behavior.
II. Core Characteristics of Duck Typing
1. Focus on behavior, not type
The most important characteristic of duck typing is that behavior comes first.
The caller focuses on what operations an object can perform, not on which class the object comes from.
def process(data):
data.save()
data.close()
This function implies two requirements:
- The object must provide a
save()method. - The object must provide a
close()method.
As long as these two conditions are met, the object can take part in the execution of this function.
This approach reduces the coupling between the caller and the concrete implementation classes.
2. No explicit inheritance required
Duck typing does not require multiple classes to share a common parent class, nor does it require an interface implementation to be declared in advance.
class FileStorage:
def save(self):
print("保存到文件")
def close(self):
print("关闭文件")
class DatabaseStorage:
def save(self):
print("保存到数据库")
def close(self):
print("关闭数据库")
def persist(storage):
storage.save()
storage.close()
FileStorage and DatabaseStorage have no inheritance relationship, but they provide the same operations, so they can be used by the same function.
Note that duck typing does not prohibit inheritance or interface declarations. It simply does not treat an explicit inheritance relationship as a necessary condition for behavioral compatibility.
3. Type compatibility usually shows up at runtime
In dynamic languages, the caller often does not check parameter types at the function's entry point; instead, it discovers whether an object meets the requirements only when the attribute is actually accessed or the method is actually called.
For example:
class User:
def save(self):
print("保存用户")
def persist(obj):
obj.save()
persist(User())
persist("hello")
The first call executes normally.
The second call raises an AttributeError because a string has no save() method.
Therefore, duck typing does not mean there are no type constraints; rather, the type constraints are reflected more in the actual operations and the behavioral contract.
III. How Duck Typing Works
Duck typing can be understood from three perspectives: the caller, the object, and runtime.
1. The caller defines the behavioral requirements
Through the operations it actually uses, the caller implicitly defines the contract that an object must satisfy.
For example:
def render(document):
document.open()
content = document.read()
document.close()
return content
This function requires the object to have:
| Behavior | Purpose |
|---|---|
open() |
Open the resource |
read() |
Read the content |
close() |
Close the resource |
No interface is explicitly declared here, but the calling code has already defined the behavioral requirements.
2. The object provides the corresponding behavior
Different objects can implement these operations in different ways.
class LocalFile:
def open(self):
print("打开本地文件")
def read(self):
return "本地文件内容"
def close(self):
print("关闭本地文件")
class RemoteDocument:
def open(self):
print("建立远程连接")
def read(self):
return "远程文档内容"
def close(self):
print("断开远程连接")
The two objects have completely different internal implementations, yet they offer compatible operations to the caller.
3. Invoking Behavior at Runtime
At execution time, the runtime resolves methods based on the object's own type and its attribute lookup rules.
flowchart TD
A["Call render(document)"] --> B["Pass in a concrete object"]
B --> C["Call document.open()"]
C --> D{"Does an open method exist?"}
D -->|"Yes"| E["Execute open"]
D -->|"No"| X["Throw AttributeError"]
E --> F["Call document.read()"]
F --> G{"Does a read method exist?"}
G -->|"Yes"| H["Execute read"]
G -->|"No"| Y["Throw AttributeError"]
H --> I["Call document.close()"]
I --> J{"Does a close method exist?"}
J -->|"Yes"| K["Execute close and return the result"]
J -->|"No"| Z["Throw AttributeError"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style X fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style Y fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style Z fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Two concepts need to be distinguished here:
- Method existence: whether the object provides the method that needs to be called.
- Behavioral correctness: whether the method does the job the caller expects.
Duck typing lets the caller depend on behavior, but it does not automatically guarantee that the behavior's semantics are correct.
For example, if two classes both implement read(), but one returns a string and the other returns an integer, they may still fail to meet the caller's actual needs.
IV. The Relationship Between Duck Typing and Interfaces
Both duck typing and interfaces can achieve polymorphism, but they differ in how contracts are established and how compatibility is judged.
1. Explicit Interfaces and Implicit Interfaces
An explicit interface usually requires a type to explicitly declare that it implements that interface.
For example, in Java:
interface Animal {
void speak();
}
class Dog implements Animal {
public void speak() {
System.out.println("汪汪");
}
}
class Cat implements Animal {
public void speak() {
System.out.println("喵喵");
}
}
static void makeSound(Animal animal) {
animal.speak();
}
Dog and Cat must declare the implementation relationship through implements Animal.
Python, by contrast, can satisfy the call requirements directly through behavior:
def make_sound(animal):
animal.speak()
No interface needs to be declared in advance.
| Comparison Dimension | Explicit Interface | Duck Typing |
|---|---|---|
| Contract Declaration | Usually declared explicitly | Usually implicit |
| Basis for Compatibility | Interface implementation relationship | Whether the required behavior is available |
| Inheritance Requirement | Depends on the language mechanism | Not required |
| When Checked | Usually includes compile-time checking | In dynamic languages, often manifests at runtime |
| Flexibility | Clear contract and explicit constraints | Flexible composition and lower coupling |
| Risk | The interface declaration may be correct, but the implementation may still have defects | Runtime problems are likely when required behavior is missing or semantics are inconsistent |
Note that an interface does not necessarily require inheritance.
For example, Go uses structural interfaces: as long as a type implements the methods required by an interface, it automatically satisfies that interface. This shares a similar structural compatibility idea with duck typing, but Go still has static type checking and explicit interface type constraints.
2. Implicit Interfaces
The behavioral contract that duck typing relies on can usually be understood as a kind of implicit interface.
For example:
def calculate_area(shape):
return shape.area()
This function implicitly requires shape to provide an area() method, and the return value must be able to participate in subsequent calculations.
The interface here is not declared through interface or abstract class; instead, it consists of the behavior actually used by the caller.
Characteristics of implicit interfaces:
- No need to define interface types centrally.
- No need to modify the inheritance structure of existing classes.
- Third-party objects can directly participate in calls.
- Contracts may be scattered across function implementations and documentation.
- Interface changes may not be easy to detect in advance.
V. Duck Typing and Structural Type Systems
Duck typing and structural typing are closely related, but the two cannot simply be regarded as completely identical.
1. Structural Typing
Structural typing determines compatibility based on the structure of a type.
For example, a type has the following structure:
type Reader = {
read(): string;
};
As long as another type has a compatible read() method, it can be assigned to Reader:
class FileReader {
read(): string {
return "文件内容";
}
}
const reader: Reader = new FileReader();
Here, FileReader is not required to explicitly declare implements Reader.
TypeScript's type compatibility mainly uses structural typing rules.
2. Differences Between the Two
| Comparison Dimension | Duck Typing | Structural Typing |
|---|---|---|
| Core Basis | The behavior actually provided by the object | Whether the type structure is compatible |
| Common Environments | Dynamic languages such as Python and Ruby | TypeScript, Go, etc. |
| How It Is Checked | Often manifests at runtime | Can be checked at compile time |
| Contract Form | Usually implicit | Can explicitly declare structural types |
| Type System Requirement | Does not require a static structural type system | Depends on the type system's structural compatibility rules |
Duck typing emphasizes behavioral compatibility when objects are actually used; structural typing emphasizes how a type system determines type compatibility based on structure.
Both weaken nominal inheritance relationships, but they operate at different levels:
- Duck typing is more of a programming style and a principle for using types.
- Structural typing is a compatibility rule of a type system.
VI. Duck Typing in Different Languages
Duck typing is not a feature unique to any one language; different languages support similar ideas through different mechanisms.
1. Python
Python is one of the most typical representatives of duck typing.
class PDFDocument:
def read(self):
return "PDF 内容"
class WordDocument:
def read(self):
return "Word 内容"
def load_document(document):
return document.read()
print(load_document(PDFDocument()))
print(load_document(WordDocument()))
Python does not require the two classes to inherit from the same interface.
In addition, Python provides mechanisms such as collections.abc and typing.Protocol to help developers make implicit behavioral contracts explicit.
2. JavaScript
JavaScript is a dynamically typed language and naturally supports programming based on object behavior.
const fileStorage = {
save() {
console.log("保存到文件");
}
};
const databaseStorage = {
save() {
console.log("保存到数据库");
}
};
function persist(storage) {
storage.save();
}
persist(fileStorage);
persist(databaseStorage);
The two objects do not share a class declaration, but both provide a save() method.
JavaScript's prototype mechanism and dynamic property access make this kind of behavior composition very natural.
3. Go
Go uses structural interfaces, but that does not mean Go is a dynamically duck-typed language.
package main
import "fmt"
type Speaker interface {
Speak()
}
type Dog struct{}
func (Dog) Speak() {
fmt.Println("汪汪")
}
type Cat struct{}
func (Cat) Speak() {
fmt.Println("喵喵")
}
func MakeSound(s Speaker) {
s.Speak()
}