Reputation: 197
In Python3, del
is a statement to be used like del x
. Why is del
not designed as a built-in function used like del(x)
?
Upvotes: 5
Views: 240
Reputation: 50076
TLDR: This is a result of use-mention distinction. A function cannot operate on the symbol x
.
The important distinction between statements and functions is that statements can work on symbols whereas functions can only work on values.
Consider a hypothetical delete
function draft:
>>> def delete(*targets):
... print("Deleting", targets, "[TODO: implement actual deletion]")
...
>>> x = "the value of x"
>>> delete(x)
Deleting ('the value of x',) [TODO: implement actual deletion]
By using x
(or an attribute x.y
, subscript x[y]
or slice x[y:z]
) in a function call, it is automatically evaluated to its value. The function only receives the value, not the symbol or even the symbol-in-its-scope – the function thus cannot delete the symbol from its scope, since it knows neither.
Python has no concept of quoting expressions, so there is no way to express "the symbol x
". It is possible to use strings to contain symbol names, such as using delattr(x, 'y')
instead of del x.y
, but not symbol context – a hypothetical delattr('x.y')
cannot work, since it does not know the initial x
's scope.
Only things built into the grammar can refer to symbols and their context. This means that del
must be at least a built-in statement or expression. In parallel to the assignment statement, which operates on the same targets, del
is a statement.
Upvotes: 8