Parentheses in Python Conditionals

Ben Keating picture Ben Keating · Jan 19, 2011 · Viewed 71.4k times · Source

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?

Answer

g.d.d.c picture g.d.d.c · Jan 19, 2011

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.