Browse OOP reference
Types and contracts

What is duck typing?

On this page

Duck typing means code uses the operations a value offers. Python code calling source.read(4096) may work with a file or a compatible adapter. A source returning text can still fail a consumer expecting bytes. Exercise the behavioural contract as well as checking that the method exists.

Worked example

Python
from io import BytesIO

def packet_size(source):
    chunk = source.read(4)
    if not isinstance(chunk, bytes):
        raise TypeError("Expected bytes")
    return len(chunk)

assert packet_size(BytesIO(b"OK")) == 2

Python data model

Explore class relationships in the OOP Playground

What are protocols?What is polymorphism?What is multiple inheritance?

All OOP questions

Search ObjectFAQ