Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The |= operator is the augmented assignment operator used for bitwise OR, set union, and dictionary merging. It evaluates the expression on its right-hand side, applies the underlying OR logic between the left-hand variable and the evaluated right-hand result, and binds the resulting value back to the left-hand variable. Under the hood, a |= b invokes the __ior__(self, other) (in-place OR) magic method on the left operand. If the left operand is a mutable type that implements __ior__, the object is modified in place. If __ior__ is not implemented (as with immutable types), Python falls back to the standard __or__(self, other) method and reassigns the result to the left variable (a = a | b).
variable |= expression
The mechanical behavior of |= depends strictly on the data type of the left-hand operand:

Integers (Bitwise OR)

When applied to integers, |= performs a bitwise OR operation on the binary representations of the operands. For each bit position, if the bit is 1 in either the left or right operand, the resulting bit is set to 1. Because integers are immutable, this operation creates a new integer object and rebinds it to the variable.
a = 10     # Binary: 1010
a |= 6     # Binary: 0110

# a is now 14 (Binary: 1110)

Sets (In-Place Union)

When the left operand is a set, |= performs an in-place union. It mutates the original set object by adding all unique elements from the right operand. Unlike the set.update() method (which accepts any iterable), the |= operator strictly requires the right-hand operand to also be a set. Attempting to use a non-set iterable (like a list or tuple) will raise a TypeError.
s = {1, 2}
s |= {2, 3, 4}  # Right operand must strictly be a set

# s is mutated to {1, 2, 3, 4}

Dictionaries (In-Place Merge)

Introduced in Python 3.9 (PEP 584), when the left operand is a dict, |= performs an in-place dictionary merge. It mutates the left dictionary by inserting key-value pairs from the right operand. In the event of key collisions, the value from the right-hand operand overwrites the value in the left-hand operand. Unlike the standard | operator (which strictly requires both operands to be mappings), the |= operator for dictionaries accepts either a mapping or any iterable of key-value pairs (such as a list of tuples) on the right-hand side, mirroring the behavior of the dict.update() method.
d = {'a': 1, 'b': 2}
d |= [('b', 99), ('c', 3)]  # Right operand can be an iterable of pairs

# d is mutated to {'a': 1, 'b': 99, 'c': 3}
Master Python with Deep Grasping Methodology!Learn More