Repaso
Español
PythonAdvancedPY-20

Which typing tool lets a type checker accept any object that has a read() method, without inheritance?

Options

  1. typing.Protocol (Correct option)
  2. abc.ABC
  3. typing.TypeVar
  4. typing.Final

Answer

typing.Protocol

Why

There are two ways to decide that a type is compatible. Nominal: the class must inherit from a base class (like an ABC). Structural: the class only needs the right methods (duck typing).

typing.Protocol gives type checkers structural typing: any object with a read() method matches a Protocol that declares read(), without inheriting from anything.

Remember

Protocol = duck typing that type checkers understand.

Key terms

Practice this question in Repaso