Skip to the solution
EasyDSA11 min read

What is duck typing in Python?

136 views

The problem

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 (or TypeError for operators) at run time, not at compile time.
  • The built-ins work the same way: len(), for, in, + and with call special methods such as __len__, __iter__, __contains__, __add__, so any class that defines them plugs into the language; file-like objects such as io.StringIO are the classic example.
  • The usual style is EAFP (try it, catch the exception) rather than LBYL (hasattr/isinstance checks first), and isinstance against 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.Protocol lets 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.

  • duck-typing
  • polymorphism

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonBehaviour over type, and the built-ins that rely on it
PythonEAFP vs LBYL vs isinstance, and where duck typing bites

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 32 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What is the walrus operator?

Continue