Implementing Interfaces in Python: ABCs and Protocols
In object-oriented programming (OOP), an interface describes the methods a class must implement to play a specific role. This set of methods expresses the interface contract. Python has no dedicated syntax for interfaces, but it gives you two mechanisms for modeling them: abstract base classes and protocols. Python’s everyday duck typing takes advantage of both.
By the end of this tutorial, you’ll understand that:
abc.ABCcombined with@abstractmethodenforces the contract at instantiation time, raising aTypeErrorwhen a subclass is missing required methods.typing.Protocoldefines a structural interface that classes satisfy without inheriting from the protocol, verified by static type checkers.- Duck typing treats any object exposing the expected methods as valid, leveraging Python’s dynamic nature.
isinstance()and