What is Python Data Model #1
48 days ago · 49 views
What is Python Data Model n.1
I started learning Python a few months ago, and now I'm getting a better grasp of the language.
Why does Python use len(my_list)? Every other language I know uses my_list.length. It felt backwards. Like Python was being difficult on purpose.
The thing that broke
I made a Book class. Simple stuff:
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
my_book = Book("1984", 328)
print(len(my_book)) # TypeError: object of type 'Book' has no len()
Right. Because I didn't give it a __len__ method.
So I tried adding a .length attribute. Then I looked at the standard library and saw some classes use __len__(), some use .count(), some use .size(). Every class had its own vocabulary.
And I realized: that's the entire point of len().
What I got wrong about functions
The function isn't wrapping a method. The function is the interface.
When you write len(obj), Python doesn't look for a .length() method. It looks for __len__(). That's the protocol. You implement __len__(), Python gives you len() for free:
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __len__(self):
return self.pages
my_book = Book("1984", 328)
print(len(my_book)) # 328
It's not about convenience. It's about consistency. Every object in Python that has a length speaks the same language. You don't need to remember if it's .length or .size or .count. You just use len().
Same with +. You don't call .add(). You implement __add__() and Python handles the rest. Same with [] and __getitem__(). Same with for loops and __iter__().
The part that still feels weird
I'm not calling __len__() directly. I never write my_book.__len__(). Python does that behind my back. It's almost like the special methods aren't for me—they're for Python. I'm just filling in the blanks so Python knows what to do when I write normal code.
And maybe that's what "Pythonic" actually means. Not writing clever code. Just making your objects fit the shape Python expects.
I don't know if I like it yet. But at least now I understand why it's there.