1

As seen in the following recipe, the |= operator is used. I've never seen it before, and it's not documented. What does it mean?

4 Answers 4

7

It's an in-place |. a |= b is mostly equivalent to a = a | b.

Sign up to request clarification or add additional context in comments.

3 Comments

And what does the | operator means? I didn't find it in the documentation as well.
With numbers it's bitwise or.
For fun, try False |= True; False
4

|= is a so called augmented assignment statement. Its purpose is to do an in-place or operation, just as the normal | operation.

There are, however, some sublte differences, as a different method of the object is called: for |, it is __or__() or __ror__(), for |=, it is __ior__().

Comments

3

In the particular recipe you're asking about:

startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW 

dwFlags is a bitmask, that is, it stores a number of flags in a single integer value by turning on the appropriate bits in the integer. In this case, STARTF_USESHOWWINDOW has a value of 1, which means that this flag is set if the least significant bit in the dwFlags integer is 1, and is not set if the LSB is 0.

What the |= operator does in this case is to take the left operand and change it so the 1 bits in the left operand are set in it, and the rest of the bits are left alone.

For example, if it has some flags set such that it's binary representation before was, say, 00101000, it will be set to 00101001, adding subprocess.STARTF_USESHOWWINDOW to the flags that are set without affecting the other flags that were set before the operation.

Comments

1

a |= b means the same as a = a | b.

3 Comments

cares to give a reason for down voting?
Probably the one has gone already. But maybe it was because of the absolute claim "the same as" - it is not the same in all circumstances. Nevertheless, I would not have downvoted (but not up as well).
E.g., in the case of sets, where | is the union of 2 sets, both statements mean sth. else: a |= b modifies the object referred by a, while a = a | b creates a new object and lets a refer it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.