akva wrote: > 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 > > For example let's consider the following code: > > def foo(s): > s = s | set([10]) > > def bar(s): > s |= set([10]) > > s = set([1,2]) > > foo(s) > print s # prints set([1, 2]) > > bar(s) > 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.
Yes. That's the exact purpose of the in-place operators when they deal with mutable objects. What else did you expect? Now of course this behaves different: def foo(x): x += 1 y = 100 foo(y) print y will result in y still being 100, as the value 101 that is bound to x inside foo is *not* re-bound to the name y in the outer scope. This is because numbers (and strings and tuples) are immutables, and thus the operation won't modify the 100 in place to become 101, instead return a new object. Diez -- http://mail.python.org/mailman/listinfo/python-list