Question

I can't find in PEPs information about style of bitwise operators (|, &), in this code in particular:

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 use spaces in this case (wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT)?

Was it helpful?

Solution 2

The place to find this, if it existed, would be Whitespace in Expressions in PEP 8. However, these operators are not mentioned:

Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).

I think there's 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 you want it in a|b. In fact, an expression like a&b | c&d seems a pretty good parallel to the recommended x*x + y*y.

The reason you want it here has nothing to do with the operator being |, but with the value being wx.SPLASH_CENTRE_ON_SCREEN. In fact, I think you'd make the same decision with BIG_LONG_CONSTANT_1 + BIG_LONG_CONSTANT_2. So, maybe there should be an additional rule in the style guide about whitespace around operators when the operands are ugly capitalized constants.

But meanwhile, I don't think there is, or needs to be, a specific rule about the bitwise operators. Treat them the same way you do the arithmetic operators. (And note that there is no specific rule for whether or not to put spaces around, e.g., +, except in the case where operators with different priorities are used in the same expression. In fact, you see it both ways within PEP8 itself. That implies that it's acceptable either way in general, and you have to use your own judgment in specific cases.)

All that said, the style checker pep8 flags both bitwise and arithmetic operators without whitespace with an E225. And it even flags the "different priorities" examples like x = x/2 - 1 (which PEP 8 lists as "good") with the optional E226 warning. See missing_whitespace_around_operator for details. I don't think this counts as any kind of official endorsement—but I think "I put the spaces here so the code would pass the style checker we've chosen to use for this project" is a pretty valid reason. (But you might want to check alternatives like pep8ify, and see if pylint, pyflakes, etc. have anything to say on the topic.)

OTHER TIPS

I would definitely use spaces on either side. Otherwise, it'd hard to spot the | in between the variable/constant names.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top