Understanding Python's Data Model - Part 3: Practical Patterns, Pitfalls & Performance Now that you understand what special methods exist, let's explore how to use them effectively in real-world scenarios, avoid common mistakes, and understand their performance implications. Practical Patterns & Real Examples Pattern 1: Building a Custom Collection Let's build a UniqueList that acts like a list but only stores unique elements: class UniqueList: """A list that automatically removes duplicates""" def __init__(self, items=None): self._items …
Read the full post →
I thought I understood __repr__ and __str__. I was wrong. Every time I needed a string representation, I'd write __str__ first. It felt natural: str() converts things to strings, so obviously that's the one you implement. Then I'd run into a situation where my object printed weirdly in a list or the debugger, and I'd get annoyed and add __repr__ as an afterthought. This is backwards. The Thing that was not clear __repr__ is not …
Read the full post →
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)) # …
Read the full post →