Python
Most people know the issue with mutable defaults in Python. But what’s the best way to fix it? The issue class User: def __init__(self, name: str, emails: list[str] = []) -> None: self.name = name self.emails = emails def add_email(self, email: str) -> None: self.emails.append(email) james = User(name="James") james.add_email("james@gmail.com") john = User(name="John") # John will have the emails ['james@gmail.com'], even though we never added that email to John's list. # That's a bug!
Let’s say you have a parent class Animal and a child class Cat that inherits from Animal. You might think that you can add a Cat to a list of Animals. But then your pyright / vscode / mypy linter will complain that you can’t do that. Why is that? Let’s start with a simple example: class Animal: def make_sound(self) -> None: print(f"animal!") class Dog(Animal): ... class Cat(Animal): ... def meow(self) -> None: print("meow!
The zip function is a built-in function in Python that allows you to combine two or more iterables into a single iterable. This is a useful function, but it has a very dangerous pitfall that can lead to very subtle bugs. It does not raise an error when the two iterables have different lengths. Instead, it will silently ignore the extra elements of the longer iterable. This can lead to very hard to track bugs (and has hurt me in the past).