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
Pythonfrom 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")) == 2Explore class relationships in the OOP Playground