Question presented to candidate: "People say Python uses duck typing. What does that mean in practice, and what are the upsides and the risks?"
What a strong answer should cover:
- Duck typing: code relies on what an object can do (its methods and attributes), not on its declared class; "if it walks like a duck and quacks like a duck, treat it as a duck".
- Python checks at the moment of use: a missing method raises
AttributeError(orTypeErrorfor operators) at run time, not at compile time. - The built-ins work the same way:
len(),for,in,+andwithcall special methods such as__len__,__iter__,__contains__,__add__, so any class that defines them plugs into the language; file-like objects such asio.StringIOare the classic example. - The usual style is EAFP (try it, catch the exception) rather than LBYL (
hasattr/isinstancechecks first), andisinstanceagainst a concrete class is the opposite of duck typing. - Trade-offs: flexible and easy to test with fakes, but errors surface late and a name can match while the meaning does not;
typing.Protocollets a type checker verify the shape statically.
Code / implementation expected: Optional β a function that accepts any object with the right method, and a class that works with len()/for because it defines the special methods.