Why does del (x) with parentheses around the variable name work in Python?

Question:

Why does this piece of code work the way it does?

x = 3
print(dir())   #output indicates that x is defined in the global scope
del (x)
print(dir())   #output indicates that x is not defined in the global scope

My understanding is that del is a keyword in Python, and what follows del should be a name. (name) is not a name. Why does the example seem to show that del (name) works the same as del name?

Asked By: Isaac To

||

Answers:

The definition of the del statement is:

del_stmt ::=  "del" target_list

and from the definition of target_list:

target_list ::=  target ("," target)* [","]
target      ::=  identifier
                 | "(" target_list ")"
                 | "[" [target_list] "]"
                 | ...

you can see that parentheses around the list of targets are allowed.

For example, if you define x,y = 1,2, all of these are allowed and have the same effect:

del x,y
del (x,y)
del (x),[y]
del [x,(y)]
del ([x], (y))
Answered By: Ohad Eytan

del statement with or without parentheses as shown below are the same:


del (x)
del x

And, other statements such as if, while, for and assert with or without parentheses as shown below are also the same:


if (x == "Hello"):
if x == "Hello":

while (x == 3):
while x == 3:

for (x) in (fruits):
for x in fruits:

assert (x == 3)
assert x == 3

In addition, basically, most example python code which I’ve seen so far doesn’t use parentheses for del, if, while, for and assert statements so I prefer not using parentheses for them.

Answered By: Kai – Kazuya Ito