Python core
In Python, a variable is only a name tag on an object. Assignment never copies, and a function gets the same object the caller has. Once you see this, the mutable default argument, shared nested lists, and "my list changed by itself" bugs become easy to spot. Then the data model, generators and type hints show how to write Python that fits the language.
Author: bezzad
Contents
The problem: a cart that fills itself
In our online shop, a new developer wrote a small helper to create a cart:
def new_cart(items=[]):
return items
alice = new_cart()
alice.append("shoes")
bob = new_cart()
print(bob) # ['shoes']
Bob never added shoes. But his new cart already has them. Nothing is broken in the language. This is how Python works with names and objects. To understand this bug, we start from the base.
Names are tags, objects live elsewhere
In Python, a variable is not a box that holds a value. It is a name that points to an object.
- The object lives in memory. It has a type, a value and an identity.
- The name is only a tag on the object. Many names can point to one object.
- Assignment never copies. The line b = a only puts a second tag on the same object.
cart = ["shoes", "hat"]
same_cart = cart # a second name for the same list
same_cart.append("bag")
print(cart) # ['shoes', 'hat', 'bag']
print(same_cart is cart) # True: one object, two names
There are two ways to compare:
- The == operator asks: “Do they have the same value?” It calls the
__eq__method. - The is operator asks: “Is it the same object?” It compares identity.
Use the is operator only for None and other singletons. For numbers and strings, always use ==. Some small numbers and strings may be shared objects, but this is a detail of CPython, not a rule you can trust.
Mutable and immutable objects
Some objects can change after they are made. Others cannot.
- Immutable: int, float, str, tuple, frozenset, bytes. Any “change” makes a new object.
- Mutable: list, dict, set, and most normal class instances. They can change in place.
price = 10
old = price
price += 5 # a new int object; old is still 10
items = ["shoes"]
old_items = items
items += ["hat"] # the same list is changed in place
print(old_items) # ['shoes', 'hat']
The same operator += gives different results. For an int, it makes a new object. For a list, it changes the list in place.
Functions get the same object
When you call a function, the parameter becomes a new name for the same object the caller passed. Python does not copy the argument.
def add_free_gift(items: list[str]) -> None:
items.append("gift card") # changes the caller's list
order = ["shoes"]
add_free_gift(order)
print(order) # ['shoes', 'gift card']
- Changing the object inside the function (append, item assignment) is seen by the caller.
- Giving the parameter a new object (assigning a new list to items) is not seen by the caller. It only moves the local tag.
- A clear rule for your code: a function should either change its argument and return None, or return a new object. Do not do both. The list.sort method and the sorted function follow this rule.
The mutable default argument trap
Now back to the cart at the start. The key fact: the default value is created once, when the def line runs, not on each call.
- When Python runs the def line, it creates one empty list and stores it on the function object.
- Each call without an argument gets that same list.
- The first caller appends “shoes” to it. The list stored on the function now has shoes.
- The next caller gets the same list, with shoes in it.
The fix is a None default, and a new list inside the function:
def new_cart(items: list[str] | None = None) -> list[str]:
if items is None:
items = [] # a fresh list on every call
return items
The same trap happens with a dict or set default, and with a default like a datetime value made by datetime.now: it is computed once, so every call gets the same time. Linters such as Ruff and Pylint warn about mutable defaults.
Shallow copy and deep copy
Sometimes you really need a copy. There are two kinds.
import copy
order = {"id": 7, "items": ["shoes", "hat"]}
shallow = copy.copy(order) # new dict, same inner list
deep = copy.deepcopy(order) # new dict, new inner list
order["items"].append("bag")
print(shallow["items"]) # ['shoes', 'hat', 'bag']
print(deep["items"]) # ['shoes', 'hat']
- A shallow copy makes a new outer object, but the inner objects are shared. The copy method of a list or dict, and a full slice of a list, are shallow.
- A deep copy copies every object inside, all the way down. It is slower, so use it only when you need it.
A famous shallow trap is multiplying a list of lists:
# Bad: three references to ONE inner list
shelves = [[]] * 3
shelves[0].append("shoes")
print(shelves) # [['shoes'], ['shoes'], ['shoes']]
# Good: three different inner lists
shelves = [[] for _ in range(3)]
The data model: dunder methods
Python calls special methods (with two underscores on each side, “dunder”) when you use built-in syntax. The len function calls __len__, a for loop calls __iter__, and == calls __eq__. If your class has these methods, it works like a built-in type.
class Cart:
def __init__(self) -> None:
self._items: dict[str, int] = {}
def add(self, sku: str, quantity: int = 1) -> None:
self._items[sku] = self._items.get(sku, 0) + quantity
def __len__(self) -> int:
return sum(self._items.values())
def __iter__(self):
return iter(self._items.items())
def __contains__(self, sku: str) -> bool:
return sku in self._items
def __repr__(self) -> str:
return f"Cart({self._items!r})"
cart = Cart()
cart.add("shoes", 2)
print(len(cart)) # 2
print("shoes" in cart) # True
for sku, quantity in cart:
print(sku, quantity)
An important rule about == and hashing:
- A set or a dict key uses
__hash__first, then__eq__. - If two objects are equal, they must have the same hash.
- If you define
__eq__but not__hash__, Python sets__hash__to None. The objects can no longer go into a set or be dict keys. - A hash must not change while the object is inside a set. So only immutable objects should be hashable.
For simple value classes, a frozen dataclass writes __init__, __repr__, __eq__ and __hash__ for you:
from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True)
class Money:
amount: Decimal
currency: str
price = Money(Decimal("19.99"), "EUR")
print(price == Money(Decimal("19.99"), "EUR")) # True
# hashable, because it is frozen
prices = {price}
Note: use Decimal for money, not float. A float cannot store 0.1 exactly.
Comprehensions
A comprehension builds a list, dict or set from another collection in one clear expression.
products = [
{"sku": "shoes", "price": 80, "in_stock": True},
{"sku": "hat", "price": 20, "in_stock": False},
{"sku": "bag", "price": 45, "in_stock": True},
]
available = [p["sku"] for p in products if p["in_stock"]]
price_by_sku = {p["sku"]: p["price"] for p in products}
# a generator expression, no list is built
total = sum(p["price"] for p in products)
- Use a comprehension to build a new collection. It is short and fast.
- Do not use it only for side effects, for example to call print or to send emails. A normal for loop is clearer there.
- Keep it short. If you need two levels of loops and several conditions, write a normal loop.
Iterators and generators
An iterable is anything you can loop over (a list, a dict, a file). An iterator is an object that gives the next item each time, and remembers where it is. A for loop asks the iterable for an iterator, then asks for the next item until the iterator says “stop”.
A generator is the easy way to write an iterator: a function with yield.
from collections.abc import Iterator
def read_orders(path: str) -> Iterator[str]:
with open(path, encoding="utf-8") as file:
for line in file:
yield line.strip() # pause here and give one line
- Calling the function does not run its body. It only returns a generator object.
- Each time the loop asks for the next item, the body runs until the next yield and pauses there.
- Local variables are kept between the pauses.
- When the body ends, the generator raises StopIteration and the loop stops.
Why is this useful? A file with 10 million orders is read one line at a time. Memory stays small.
The trap: a generator works only once.
orders = (o for o in ["A1", "A2", "A3"])
print(list(orders)) # ['A1', 'A2', 'A3']
print(list(orders)) # [] the generator is already used up
If you need the items twice, keep them in a list, or call the generator function again.
Type hints
Type hints say what types a function expects and returns. Python itself does not check them at runtime. Tools like mypy and Pyright check them before the code runs, and your editor uses them for help.
from collections.abc import Iterable
from decimal import Decimal
def order_total(
prices: Iterable[Decimal],
discount: Decimal | None = None,
) -> Decimal:
total = sum(prices, start=Decimal("0"))
if discount is not None:
total -= discount
return total
# generic function, syntax from Python 3.12
def first[T](items: list[T]) -> T:
return items[0]
- Use the built-in types list and dict directly in hints, with the item type in square brackets. You do not need to import List or Dict from the typing module.
- For “a value or None”, put the pipe sign between the type and None, as in the code above.
- Accept wide types and return exact types. Take Iterable when you only loop, and return list when you build a list.
- Hints do not validate data. If data comes from outside (JSON, a form), validate it, for example with Pydantic.
- Since Python 3.14, annotations are evaluated lazily, only when someone reads them. So a class can name a type that is defined later in the file without quotes.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| A list or dict as a default argument | Every call shares one object. | Default None, and make a new object inside. |
| Thinking b = a makes a copy | A change through b is seen through a. | Copy on purpose: the copy method, or copy.deepcopy. |
| Multiplying a list of lists | All rows are the same inner list. | A list comprehension. |
| Comparing numbers or strings with is | Works sometimes, fails sometimes. | Use ==. Use is only for None. |
Defining __eq__ without thinking about __hash__ |
Objects cannot go into a set or dict. | A frozen dataclass, or a matching __hash__. |
| Looping twice over a generator | The second loop sees nothing. | Keep the items in a list, or call the function again. |
| Expecting type hints to stop bad data | Wrong data passes silently. | Run mypy or Pyright in CI, and validate input. |
| float for money | Small rounding errors in totals. | Decimal. |
Summary in 7 lines
- A variable is a name on an object. Assignment and function calls never copy.
- Mutable objects (list, dict, set) can change in place. Every name that points to them sees the change.
- A default argument is created once, when def runs. Use None as the default for mutable values.
- A shallow copy shares the inner objects. A deep copy does not.
- Dunder methods connect your class to Python syntax. Equal objects must have equal hashes.
- A generator is lazy and works only once. It keeps memory small for big data.
- Type hints are for tools and readers. Python does not check them at runtime.