Suppose we have in Python 3.x (and I guess in Python 2.6 and in Python 2.7 too) the following functions:
>>> def dbl_a(p): return p*2
>>> d
There are generally 4 uses for the parentheses ()
in Python.
\
. This is mostly stylistic.
decision = (is_female and under_30 and single
or
is_male and above_35 and single)
the parenthesis is an alternative syntax to avoid hitting the 80 column limit and having to use \
for statement continuation.
In any other cases, such as inside the if
, while
, for
predicates and the return
statement I'd strongly recommend not using ()
unless necessary or aid readability (defined by the 4 points above). One way to get this point across is that in math, (1)
and just 1
means exactly the same thing. The same holds true in Python.
People coming from the C-family of languages will take a little bit getting used to this because the ()
are required in control-flow predicates in those languages for historical reasons.
Last word for return
statements, if you are only returning 1 value, omit the ()
. But if you are returning multiple values, it's OK to use ()
because now you are returning a grouping, and the ()
enforces that visually. This last point is however stylistic and subject to preference. Remember that the return
keywords returns the result of a statement. So if you only use ,
in your multiple assignment statements and tuple constructions, omit the ()
, but if you use ()
for value unpacking and tuple constructions, use ()
when you are returning multiple values in return
. Keep it consistent.