The | operator between objects
Between two objects, | is not always a bitwise 'or': each type decides what it means, and for dicts and sets it merges their contents.
Used in 24 lessons of the course, from 01.01.
Python lets each type define what an operator does. This is called operator overloading. When you write a | b, Python calls the special method a.__or__(b).
With integers, | is a bitwise "or". With dicts, it builds a new dict with the keys of both. If a key is in both, the right-hand value wins. With sets, it returns the union.
The originals are not changed. That's why it fits a line like rows.append({"role": role} | info): you build a new dict with role plus everything in info, without modifying info.
You can also define __or__ in your own classes. Some libraries do this to chain steps, so a | b reads as "a, and then b".
{"a": 1} | {"b": 2} # {'a': 1, 'b': 2}
Reach for it when: you want to merge two dicts or sets into a new object without touching the originals, or when you read code that chains objects with `|`.
Examples
Common mistake
a = {"x": 1}
print(a | [("y", 2)])Why: The dict `|` only accepts another dict. A list of tuples won't work.
How to write it: Convert it first: a | dict([("y", 2)]).
Common mistake
defaults = {"mode": "fast"}
user = {"mode": "slow"}
print(user | defaults)Why: The right side wins. The defaults overwrote what the user chose.
How to write it: Put the defaults on the left: defaults | user.
