Python Pipe Character for calling functions

526 views Asked by At

just a simple question.

Some python functions I have seen are called like this, for example pygame:

pygame.display.set_mode((255, 255), FULLSCREEN) This seems normal to me.

But when you want to use more than one argument, you must use |. For example: pygame.display.set_mode((255, 255), FULLSCREEN | HWSURFACE | DOUBLEBUF)

When and why would you want this kind of calling? I have heard it is the bitwise OR operator, but it seems that is only for boolean values. How does this work?

2

There are 2 answers

0
Nolen Royalty On BEST ANSWER

They're flags for different options. Each flag is just a number, specifically a power of 2. You use the bitwise operator | to flip the bits for all the flags you want. An example might help:

>>> import re
>>> re.VERBOSE
64
>>> re.IGNORECASE
2
>>> re.VERBOSE | re.IGNORECASE
66

so if re wants to know whether the IGNORECASE flag is set it can just check whether the second bit(for 2^1) is equal to 1. If so, we should ignore case. And if it wants to know whether to be VERBOSE, it checks the 7th bit(for 2^6). By oring 2 and 64 together, you have a number with the second and seventh bits flipped.

>>> 66 & 2
2
>>> 66 & 64
64
>>> 66 & 8
0

We can see that 66 triggers flags for 2 and 64, but not 8.

2
Elias Dorneles On

Beware the difference between bitwise OR operator with the boolean OR operator:

| is the bitwise OR operator, that is, the OR operation is made bit per bit of the operands:

>>> 1 | 2
3

That's because 1 binary is 001, 2 binary is 010, so the OR bit per bit of them is 011, that is, 3.

or is the boolean operator.

>>> 1 or 2
1
>>> 0 or 2
2

The or operator returns the first valid value (not 0, None, [] or {})