Protocols in Python

1. define

  • protocol is a set of operations that a type must support to implement
  • they do not need to be defined as separate interfaces or base classes
  • that would be the case in nominally typed languages such as C# or Java
  • it is enough to provide functioning implementations of these operations
  • protocol support demands specific behavior

2. container protocol requirements

  • requirement: membership testing using in and not in

3. sized protocol requirements

  • requirement: length of a type by checking with len(container)

4. iterable protocol requirements

  • yield items one by one as they are requested
  • iterable is an object from which you can fetch a sequence of other objects
  • the act of fetching from an iterable is known as iteration
  • they can be used in for loops

5. sequence protocol requirements

  • items can be retrieved using []
  • items can be searched-for with sequence.idex(item)
  • items can be counted with sequence.count()
  • reversed copy can be produced with reversed(sequence)
  • must support iterable + sized + container



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: