Bitwise Operator Style in Python

I cannot find any information in the PEP about the style of the bitwise operators (|, &) in this code, specifically:

class MySplashScreen(wx.SplashScreen):
    def __init__(self, parent=None):
        wx.SplashScreen.__init__(self, logo.getBitmap(), wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, 2000, parent)

      

Should I be using spaces in this case ( wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT )?

+3


source to share


2 answers


The place to look, if it exists, would be Space in expressions in PEP 8. However, these operators are not mentioned:

Always surround these binary operators with the same space on both sides: assignment (=), extended assignment (+ =, - =, etc.), comparisons (==, <,>,! =, <>, <=,> =, in, not in, is, is not), Booleans (and, or, not).

I think there is a good reason for this. While you almost certainly want the space in wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT

, I'm not sure what you want it in a|b

. In fact, the type expression a&b | c&d

seems to parallel the recommended one pretty well x*x + y*y

.



The reason you want here has nothing to do with what the operator is |

, but with the value wx.SPLASH_CENTRE_ON_SCREEN

. In fact, I think you would make the same decision with BIG_LONG_CONSTANT_1 + BIG_LONG_CONSTANT_2

. So, perhaps the style guide should add a rule about whitespace around operators when the operands are ugly capitalized constants.

But for now, I don't think there is or should be a specific rule about bitwise operators. Treat them the same way as you would arithmetic operators. (Note that there is no specific rule for placing whitespace, for example, +

except when operators with different precedence are used in the same expression. In fact, you see this both ways in PEP8. This implies that this is generally acceptable anyway, and you should use your own judgment in specific cases.)

All that said, the style check pep8

contains flags both bitwise and non-whitespace arithmetic operators since E225. And that even means examples of "different priorities", for example x = x/2 - 1

(which PEP 8 displays as "good") with additional warning E226. For details see missing_whitespace_around_operator

. I don't think this counts as an official endorsement, but I think "I put spaces here so the code would pass the style check we chose to use for this project" is a pretty good reason. (But you can check out alternatives like pep8ify

, and see if this thread has pylint

, pyflakes

etc.)

+1


source


I would definitely use spaces on both sides. Otherwise it would be difficult to tell |

between variable / constant names.



+2


source







All Articles