Parentheses in Python Conditionals

I have a simple question regarding the use of parentheses in Python's conditional statements.

The following two snippets work just the same but I wonder if this is only true because of its simplicity:

>>> import os, socket
>>> if ((socket.gethostname() == "bristle") or (socket.gethostname() == "rete")):
...     DEBUG = False
... else:
...     DEBUG = True
... 
>>> DEBUG

and now without parentheses

>>> import os, socket
>>> if socket.gethostname() == "bristle" or socket.gethostname() == "rete":
...     DEBUG = False
... else:
...     DEBUG = True
... 
>>> DEBUG

Could anyone help shed some light on this? Are there any cases where I should definitely use them?


Solution 1:

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.

Solution 2:

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):
    ...