Thanks to visit codestin.com
Credit goes to www.pythonmorsels.com

Unnecessary parentheses in Python

Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
5 min. read Python 3.10—3.14
Share
Copied to clipboard.

Python's if statements don't use parentheses, and yet this is valid Python code:

if (language == "Python"):
    print("[Insert Monty Python joke] (that's the joke)")

Python doesn't have type casting, but this (strangely) also valid code:

>>> n = 3.4
>>> m = (int)(n)
>>> m
3

In Python, parentheses can be used for function calls, for making (empty) tuples, and for grouping. The unnecessary parentheses above are misplaced grouping parentheses.

Let's talk about where you don't need parentheses in Python.

Parentheses can be used for grouping

Parentheses are used for 3 things in Python: calling callables, creating empty tuples, and grouping.

Functions, classes, and other [callable][] objects can be called with parentheses:

>>> print("I'm calling a function")
I'm calling a function

Empty tuples can be created with parentheses:

>>> empty = ()

Lastly, parentheses can be used for grouping:

>>> 3 * (4 + 7)
33

Sometimes parentheses are necessary to convey the order of execution for an expression. For example, 3 * (4 + 7) is different than 3 * 4 + 7:

>>> 3 * (4 + 7)
33
>>> 3 * 4 + 7
19

Those parentheses around 4 + 7 are for grouping that sub-expression, which changes the meaning of the larger expression.

All confusing and unnecessary uses of parentheses are caused by this third use: grouping parentheses.

Python's if statements don't use parentheses

In JavaScript if statements look like this:

if (language == "Python") {
    console.log("[Insert Monty Python joke] (that's the joke)")
}

In Python, they look like this:

if (language == "Python"):
    print("[Insert Monty Python joke] (that's the joke)")

Or do they?

Python's if statements don't use parentheses. So if statements actually look like this:

if language == "Python":
    print("[Insert Monty Python joke] (that's the joke)")

Sometimes folks learn this fact and think "ah so the parentheses are optional". But that's not the case.

Python's if statements simply don't use parentheses.

Parentheses can go anywhere

Pretty much any Python expression can be wrapped in parentheses.

For example, all of these expressions do the same thing:

>>> x = 3
>>> y = 3 * 4 + 7
>>> y = (3 * 4) + 7
>>> y = ((3 * 4) + 7)
>>> y = ((3 * 4) + (7))
>>> y = (((((3) * (4))) + ((7))))

Grouping parentheses can be wrapped around anything, regardless of whether they're useful.

Parentheses for wrapping lines

Parentheses can also allow expressions to be wrapped over multiple lines of code. This is called an implicit line continuation.

For example, here's an if statement with a long condition that's wrapped over multiple lines:

from datetime import datetime

event = {"name": "Intro", "date": datetime(2030, 3, 6), "full": False}
user = {"name": "jill", "verified": True, "role": "admin", "perms": ["edit"]}

if (user["verified"]
        and event["date"] > datetime.now()
        and not event["full"]):
    print("Here's the event signup form...")

The parentheses in this if statement are necessary for Python to understand that we're spanning one expression over multiple lines of code.

But often, parentheses are added just for the sake of readability. And that's fine as well.

Let's look at a few more common cases of unnecessary parentheses.

Parentheses that make statements look like functions

The parentheses in this del statement make it look like a function call:

>>> colors = {"purple": 4, "blue": 2}
>>> del(colors["purple"])

But del is a statement, not a function. So those parentheses are a bit misleading. Those are grouping parentheses, not function call parentheses.

The del statement doesn't use parentheses:

>>> colors = {"purple": 4, "blue": 2}
>>> del colors["purple"]

It is possible to use parentheses with the del statement, but I don't recommend it as it could cause someone reading your code to think a function is being used rather than a statement.

Parentheses can also make return statements look like function calls.

This makes return look like it's a function:

def cube_root(n):
    return(n**(1/3))

But it's actually a statement:

def cube_root(n):
    return n**(1/3)

Sometimes you may actually want parentheses with return.

For example, here's a parse_mass function which accepts a string representing a number of grams or kilograms and returns a 2-item tuple of the quantity along with the unit:

>>> parse_mass("5kg")
(5, 'kg')

This function has a return statement that's a little involved:

import re

UNITS_RE = re.compile(r'^(?P<quantity>\d+)\s*(?P<units>kg|g)$')


def parse_mass(string):
    """Given mass in g or kg, return (quantity, unit) tuple."""
    match = UNITS_RE.search(string)
    if not match:
        raise ValueError(f"{string!r} does not contain units 'g' or 'kg'")
    return int(match['quantity']), match['units']

Putting parentheses around the 2 items in the returned tuple might make it a bit clearer that a tuple is being returned:

import re

UNITS_RE = re.compile(r'^(?P<quantity>\d+)\s*(?P<units>kg|g)$')


def parse_mass(string):
    """Given mass in g or kg, return (quantity, unit) tuple."""
    match = UNITS_RE.search(string)
    if not match:
        raise ValueError(f"{string!r} does not contain units 'g' or 'kg'")
    return (int(match['quantity']), match['units'])

If you do use parentheses with return be sure to at least put a space between return and the value.

def cube(n):
    return (n ** 3)

That makes it look a lot less a function call.

Parentheses can go in lots of places

Take a look at this code:

>>> n = 3.4
>>> m = (int)(n)

That (int) looks like type casting from Java or a similar programming language, but we're not type casting... we're calling the int function.

That code is equivalent to this:

>>> n = 3.4
>>> m = int(n)

We were just wrapping the int variable in parentheses before we call the function object that it points to (yes functions are object and variables are pointers in Python).

So that's valid for the same reason that this code is valid:

>>> (print) ("This will be printed")
This will be printed

This code is perfectly valid but please don't write it. Python will be happy with it, but other programmers will probably find it pretty confusing.

Use parentheses sometimes

Parentheses can be added in plenty of places that they shouldn't be, but you shouldn't always remove parentheses that aren't strictly necessary.

Sometimes parentheses can improve readability.

I find this:

SENTENCE_END_CHARS = ('.', '?', '!')

Slightly more readable than this:

SENTENCE_END_CHARS = '.', '?', '!'

Though I find this:

for (color, amount) in colors.items():
    print(color, amount)

About as readable as this:

for color, amount in colors.items():
    print(color, amount)

When exactly parentheses improve readability is a bit fuzzy and it's definitely subjective.

Consider readability when adding or removing parentheses

When writing an if statement, I recommend not putting parentheses around the condition unless you need to for the sake of an implicit line continuation.

And in general, consider readability when it comes to adding or removing parentheses. I usually avoid parentheses when I can, but they do definitely improve readability sometimes.

A Python Tip Every Week

Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.