简体   繁体   English

rthon中的r替换的rm()函数

[英]rm() function of r alternative in python

How to remove the variables in python to clear ram memory in python? 如何在python中删除变量以清除python中的ram内存?

R : R

a = 2 
rm(a)

python : python

a= 2

How to clear the single variables or a group of variables? 如何清除单个变量或一组变量?

Use del 使用del

>>> a=2
>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

python memory cleanup is managed by the garbage collector. python内存清理由垃圾收集器管理。 on CPython it is based on reference counting. 在CPython上它基于引用计数。 you can call the garbage collector explicitly like this: 你可以像这样明确地调用垃圾收集器:

import gc
gc.collect()

this can be done after calling a function that uses large variables in terms of ram. 这可以在调用使用ram方面的大变量的函数之后完成。 Note that you do not have to call this function explicitly as the garbage collector will be called eventually to free up ram automatically. 请注意,您不必显式调用此函数,因为最终将调用垃圾收集器以自动释放ram。

if you still want to explicitly remove a variable you can use the del statement (as written before) like this: 如果您仍想显式删除变量,可以使用del语句(如前所述),如下所示:

x = [1, 2, 3]
i = 42
s = 'abc'

del s  # delete string
del x[1]  # delete single item in a list
del x, i  # delete multiple variables in one statement

del statement del声明

to better understand what del does and its limitations lets take a look at how python stores variables on ram. 为了更好地理解del做了什么,它的局限性让我们看看python如何在ram上存储变量。

x = [1, 2, 3]

the above code creates a reference between the name x to the list [1, 2, 3] which is stored on the heap. 上面的代码在名称x到列表[1, 2, 3]之间创建了一个存储在堆上的引用。 x is just a pointer to that list. x只是指向该列表的指针。

x = [1, 2, 3]
y = x
x is y  # True

in this example we have the reference x and the list on the heap [1, 2, 3] , but what is this new y variable? 在这个例子中,我们有参考x和堆上的列表[1, 2, 3] ,但是这个新的y变量是什么? its just another pointer, meaning now we have two pointers to the same [1, 2, 3] list. 它只是另一个指针,意味着现在我们有两个指向相同[1, 2, 3]列表的指针。

returning to the del statement, if we delete one variable it wont affect the list or the other variable 返回del语句,如果我们删除一个变量,它不会影响列表或其他变量

x = [1, 2, 3]
y = x
del x
print(y)  # prints [1, 2, 3]

so here we will not free up the list, only decrease the reference counting to the list but we still have y pointing to it. 所以在这里我们不会释放名单,仅减少引用计数到列表中,但我们仍然有y指向它。

to overcome this we can use the weakref module to point y to the list and when x is deleted the list is also deleted. 为了解决这个问题,我们可以使用weakref模块将y指向列表,当删除x时,列表也会被删除。

Bottom line 底线

  • use gc.collect() after heavy memory functions 在重度记忆功能之后使用gc.collect()
  • use del x, y to delete all pointers to a specific object to free it up 使用del x, y删除指向特定对象的所有指针以将其释放
  • use weakref module to avoid holding objects on the ram after all other references to them are deleted 使用weakref模块以避免在删除所有其他对它们的引用后保持ram上的对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM