我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。

在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?


当前回答

显式使用"del"也是比将变量赋值为None更好的实践。如果你试图删除一个不存在的变量,你会得到一个运行时错误,但如果你试图将一个不存在的变量设置为None, Python会无声地将一个新变量设置为None,让你想要删除的变量留在原来的位置。所以del会帮助你尽早发现错误

其他回答

显式使用"del"也是比将变量赋值为None更好的实践。如果你试图删除一个不存在的变量,你会得到一个运行时错误,但如果你试图将一个不存在的变量设置为None, Python会无声地将一个新变量设置为None,让你想要删除的变量留在原来的位置。所以del会帮助你尽早发现错误

Del经常出现在__init__.py文件中。任何在__init__.py文件中定义的全局变量都将自动“导出”(它将包含在from模块import *中)。避免这种情况的一种方法是定义__all__,但这可能会很混乱,并不是每个人都使用它。

例如,如果你在__init__.py中有这样的代码

import sys
if sys.version_info < (3,):
    print("Python 2 not supported")

然后您的模块将导出sys名称。你应该写

import sys
if sys.version_info < (3,):
    print("Python 2 not supported")

del sys

我发现del有用的一个地方是清除for循环中的无关变量:

for x in some_list:
  do(x)
del x

现在你可以确定,如果你在for循环之外使用x,它将是没有定义的。

del is the equivalent of "unset" in many languages and as a cross reference point moving from another language to python.. people tend to look for commands that do the same thing that they used to do in their first language... also setting a var to "" or none doesn't really remove the var from scope..it just empties its value the name of the var itself would still be stored in memory...why?!? in a memory intensive script..keeping trash behind its just a no no and anyways...every language out there has some form of an "unset/delete" var function..why not python?

我发现在使用Numpy处理大数据时,del对于伪手动内存管理非常有用。例如:

for image_name in large_image_set:
    large_image = io.imread(image_name)
    height, width, depth = large_image.shape
    large_mask = np.all(large_image == <some_condition>)
    # Clear memory, make space
    del large_image; gc.collect()

    large_processed_image = np.zeros((height, width, depth))
    large_processed_image[large_mask] = (new_value)
    io.imsave("processed_image.png", large_processed_image)

    # Clear memory, make space
    del large_mask, large_processed_image; gc.collect()

当Python GC无法跟上时,系统会疯狂地切换,这可能会导致脚本停止,而它在宽松的内存阈值下运行得非常流畅,从而在机器工作时留下了足够的空间来使用机器浏览和编码。