我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
当前回答
另一个小众案例,但很有用。
from getpass import getpass
pass = getpass()
token = get_auth_token(pass)
del pass
# Assume more code here...
在删除pass变量之后,您不会冒它稍后被错误打印出来的风险,或者以其他方式结束在日志或堆栈跟踪中。
其他回答
del所做的部分(来自Python语言参考):
删除名称将从本地或全局名称空间删除该名称的绑定
将None赋值给名称不会删除名称与名称空间的绑定。
(我想关于移除名称绑定是否真的有用可能会有一些争论,但这是另一个问题。)
del在python中什么时候有用?
您可以使用它来删除数组中的单个元素,而不是切片语法x[i:i+1]=[]。这可能是有用的,例如,如果你在操作系统。行走并希望删除目录中的一个元素。不过,我不认为关键字对此有用,因为可以使用[].remove(index)方法(.remove方法实际上是search-and-remove-first-instance-of-value)。
有一次我不得不使用:
del serial
serial = None
因为只使用:
serial = None
没有及时释放串口,无法立即再次打开。 从这一课中,我了解到del的真正意思是:“现在就开始!然后等待直到它完成”这在很多情况下都很有用。当然,你可能有一个system.gc.del_this_and_wait_balbalba (obj)。
我想详细说明公认的答案,以强调将变量设置为None与使用del删除变量之间的细微差别:
给定变量foo = 'bar',函数定义如下:
def test_var(var):
if var:
print('variable tested true')
else:
print('variable tested false')
一旦初始声明,test_var(foo)产生的变量测试为true。
现在试一试:
foo = None
test_var(foo)
它产生的变量测试为假。
将这种行为与以下行为进行对比:
del foo
test_var(foo)
现在会引发NameError: name 'foo'没有定义。
I think one of the reasons that del has its own syntax is that replacing it with a function might be hard in certain cases given it operates on the binding or variable and not the value it references. Thus if a function version of del were to be created a context would need to be passed in. del foo would need to become globals().remove('foo') or locals().remove('foo') which gets messy and less readable. Still I say getting rid of del would be good given its seemingly rare use. But removing language features/flaws can be painful. Maybe python 4 will remove it :)