candleindark candleindark - 1 year ago 37
Python Question

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

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
is a keyword in Python, and what follows
should be a name.
is not a name. Why does the example seem to show that
del (name)
works the same as
del name

Answer Source

The definition of the del statemant 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 those are allowed and has the same affect:

del x,y,
del (x,y)
del (x),[y]
del [x,(y)]
del ([x], (y))