How does Python get the length with len() function?
summary
Shows that len() calls __len__ and enforces an int return, raising TypeError if __len__ returns non-int and OverflowError for absurdly large values. Demonstrates with lists, dicts and custom classes (including one that returns changing or non-int lengths) and confirms behavior by reading the CPython source and design/history FAQ and PEPs. Frames len as an adapter pattern that validates and converts object-provided length semantics, and shows the bool logic uses __bool__ or falls back to __len__ with the same checks.
AI-written summary · about
chapters (7)
- 0:00Introduction
- 2:55How len() works
- 6:36Adapter pattern and len()
- 11:21Protocols and len()
- 15:58bool() adapter
- 21:04Summary
- 25:07Q&A
related talks
31mPython Data Model
25mWhy len 4 and other weird things you should know about strings in Python
24mWhy `len('😶🌫️') == 4` and other weird things you should know about strings in Python
31mPlaying with CPython Objects Internals
01h 18mPython 103: Mmmm... Understanding Python's Memory Model, Mutability, and Methods
16mUnder and Dunder - Python secret functions
27mPython Oddities Explained
46mOn Being Pythonic
