semantics of the |= operator
tjreedy at udel.edu
Thu Aug 21 23:16:40 CEST 2008
> Hi All,
> what's the exact semantics of the |= operator in python?
> It seems that a |= d is not always equivalent to a = a | d
The manual explicitly specifies that mutable objects may implement the
operation part of operation-assignments by updating in place -- so that
the object assigned is a mutated version of the original rather than a
The value equivalency only applies in the namespace in which the
> For example let's consider the following code:
> def foo(s):
> s = s | set()
> def bar(s):
> s |= set()
> s = set([1,2])
> print s # prints set([1, 2])
Put the print inside foo and you will get set([1,2,10]), as with bar.
> print s # prints set([1, 2, 10])
> So it appears that inside bar function the |= operator modifies the
> value of s in place rather than creates a new value.
This has nothing to do with being inside a function.
More information about the Python-list