Parentheses in Python Conditionals Parentheses in Python Conditionals python python

Parentheses in Python Conditionals


The other answers that Comparison takes place before Boolean are 100% correct. As an alternative (for situations like what you've demonstrated) you can also use this as a way to combine the conditions:

if socket.gethostname() in ('bristle', 'rete'):  # Something here that operates under the conditions.

That saves you the separate calls to socket.gethostname and makes it easier to add additional possible valid values as your project grows or you have to authorize additional hosts.


The parentheses just force an order of operations. If you had an additional part in your conditional, such as an and, it would be advisable to use parentheses to indicate which or that and paired with.

if (socket.gethostname() == "bristle" or socket.gethostname() == "rete") and var == condition:    ...

To differentiate from

if socket.gethostname() == "bristle" or (socket.gethostname() == "rete" and var == condition):    ...


The parentheses are redundant in this case. Comparison has a higher precedence than Boolean operators, so the comparisons will always be performed first regardless of the parentheses.

That said, a guideline I once saw (perhaps in Practical C Programming) said something like this:

  1. Multiplication and division first
  2. Addition and subtraction next
  3. Parentheses around everything else

(Yes, IIRC they left out exponentiation!)

The idea being that the precedence rules are arcane enough that nobody should be expected to remember them all, neither the original programmer nor the maintenance programmer reading the code, so it is better to make it explicit. Essentially the parentheses serve both to communicate the intent to the compiler and as documentation for the next schmoe who has to work on it.

I believe in Python those two statements will generate the same bytecode so you're not even losing any efficiency.