Python Protocols: Len, Contains, and Iterate

How does len() function knows how to handle a List, a String, and a Dictionary all the same way in Python? TL;DR: Python Protocols A Protocol is just the set of rules (special methods) an object follows. "Duck Typing" Contract In Python does not care about what the object is, it cares only about what it does. These are represented as dunders (__method__) in Python. 3 Protocols we use everyday in Python: -> Sized (__len__): Tells Python that object has a size. (Powers len()) -> Container (__contains__): Tells Python how to check if something is "inside" the object. (Powers the in keyword) -> Iterable (__iter__): Tells Python that object can be looped over. (Powers for x in obj) Why is this useful? As a developer, we want our code to be intuitive. By following these protocols, we make our custom objects compatible with all of Python’s built-in tools. Protocols are the API of the Python language itself. Using them make custom objects start feeling like native Python parts. I’m deep-diving into the Python protocols this week and will share my learnings. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment

  • graphical user interface, text, application, email

To view or add a comment, sign in

Explore content categories