python 在python中对局部变量使用显式del

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2192926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:00:32  来源:igfitidea点击:

Using explicit del in python on local variables

pythoncoding-style

提问by abbot

What are the best practices and recommendations for using explicit delstatement in python? I understand that it is used to remove attributes or dictionary/list elements and so on, but sometimes I see it used on local variables in code like this:

del在 python 中使用显式语句的最佳实践和建议是什么?我知道它用于删除属性或字典/列表元素等,但有时我在代码中看到它用于局部变量,如下所示:

def action(x):
    result = None
    something = produce_something(x)
    if something:
        qux = foo(something)
        result = bar(qux, something)
        del qux
    del something
    return result

Are there any serious reasons for writing code like this?

编写这样的代码有什么严重的原因吗?

Edit: consider quxand somethingto be something "simple" without a __del__method.

编辑:考虑quxsomething成为没有__del__方法的“简单” 。

回答by Alex Martelli

I don't remember when I last used del-- the need for it is rare indeed, and typically limited to such tasks as cleaning up a module's namespace after a needed importor the like.

我不记得我上次使用是什么时候del- 确实很少需要它,并且通常仅限于在需要之后清理模块的命名空间等任务import

In particular, it's nottrue, as another (now-deleted) answer claimed, that

特别是,正如另一个(现已删除的)答案所声称的那样,事实并非如此

Using delis the only way to make sure a object's __del__method is called

使用del是确保__del__调用对象方法的唯一方法

and it's very important to understand this. To help, let's make a class with a __del__and check when it is called:

理解这一点非常重要。为了提供帮助,让我们用 a 创建一个类__del__并检查它何时被调用:

>>> class visdel(object):
...   def __del__(self): print 'del', id(self)
... 
>>> d = visdel()
>>> a = list()
>>> a.append(d)
>>> del d
>>>

See? deldoesn't "make sure" that __del__gets called: delremoves one reference, and only the removal of the lastreference causes __del__to be called. So, also:

看? del不“确保”__del__被调用:del删除一个引用,只有删除最后一个引用__del__才会被调用。所以,还有:

>>> a.append(visdel())
>>> a[:]=[1, 2, 3]
del 550864
del 551184

when the last reference does go away (including in ways that don't involve del, such as a slice assignment as in this case, or other rebindings of names and other slots), then__del__gets called -- whether delwas ever involved in reducing the object's references, or not, makes absolutelyno difference whatsoever.

当最后一个引用确实消失时(包括不涉及的方式del,例如在这种情况下的切片分配,或名称和其他插槽的其他重新绑定),然后__del__被调用 - 是否del曾参与减少对象的引用与否,绝对没有任何区别。

So, unless you specifically need to clean up a namespace (typically a module's namespace, but conceivably that of a class or instance) for some specific reason, don't bother with del(it can be occasionally handy for removing an item from a container, but I've found that I'm often using the container's popmethod or item or slice assignment even for that!-).

因此,除非您出于某种特定原因特别需要清理命名空间(通常是模块的命名空间,但可以想象的是类或实例的命名空间),否则不要打扰del(它偶尔可以方便地从容器中删除项目,但我发现,我经常使用的容器的pop方法或项目或切片分配甚至- !)。

回答by Jason Orendorff

No.

不。

I'm sure someone will come up with some silly reason to do this, e.g. to make sure someone doesn't accidentally use the variable after it's no longer valid. But probably whoever wrote this code was just confused. You can remove them.

我敢肯定有人会想出一些愚蠢的理由来这样做,例如确保有人不会在变量不再有效后意外使用它。但可能写这段代码的人只是感到困惑。您可以删除它们。

回答by user4034077

When you are running programs handling really large amounts of data ( to my experience when the totals memory consumption of the program approaches something like 1GB) deleting some objects: del largeObject1 del largeObject2 … can give your program the necessary breathing room to function without running out of memory. This can be the easiest way to modify a given program, in case of a “MemoryError” runtime error.

当您正在运行处理大量数据的程序时(根据我的经验,当程序的总内存消耗接近 1GB 时)删除一些对象: del largeObject1 del largeObject2 … 可以为您的程序提供必要的喘息空间来运行而不会耗尽的记忆。这可能是修改给定程序的最简单方法,以防出现“MemoryError”运行时错误。

回答by user3054603

Actually, I just came across a use for this. If you use locals() to return a dictionary of local variables (useful when parsing things) then del is useful to get rid of a temporary that you don't want to return.

实际上,我只是遇到了这个用途。如果您使用 locals() 返回局部变量字典(在解析事物时很有用),那么 del 可用于摆脱您不想返回的临时变量。