如何及早删除函数参数? [英] How to delete a function argument early?
问题描述
我正在编写一个函数,该函数需要大量参数并且可以运行很长时间。它只需要一半的参数。如果没有更多引用,该函数是否可以删除该参数所指向的值?
I'm writing a function which takes a huge argument, and runs for a long time. It needs the argument only halfway. Is there a way for the function to delete the value pointed to by the argument if there are no more references to it?
我能够尽快将其删除函数返回,如下所示:
I was able to get it deleted as soon as the function returns, like this:
def f(m):
print 'S1'
m = None
#__import__('gc').collect() # Uncommenting this doesn't help.
print 'S2'
class M(object):
def __del__(self):
print '__del__'
f(M())
此打印:
S1
S2
__del__
我需要:
S1
__del__
S2
我也在尝试 def f(* args):
和 def f(** kwargs)
,但这并没有帮助,最后我仍然得到 __ del __
。
I was also trying def f(*args):
and def f(**kwargs)
, but it didn't help, I still get __del__
last.
请注意我的代码依赖于Python具有引用计数这一事实,并且 __ del __
在对象的引用计数降至零时立即被调用。我希望函数参数的引用计数在函数中间降至零。
Please note that my code is relying on the fact that Python has reference counting, and __del__
gets called as soon as an object's reference count drops to zero. I want the reference count of a function argument drop to zero in the middle of a function. Is this possible?
请注意,我知道一种解决方法:传递参数列表:
Please note that I know of a workaround: passing a list of arguments:
def f(ms):
print 'S1'
del ms[:]
print 'S2'
class M(object):
def __del__(self):
print '__del__'
f([M()])
此打印:
S1
__del__
S2
是否可以在不更改API的情况下(例如在参数列表中引入)来实现早期删除?
Is there a way to get the early deletion without changing the API (e.g. introducing lists to the arguments)?
如果很难获得可在许多Python实现中使用的便携式解决方案,那么我需要在最新的CPython 2.7中可以使用的解决方案。
If it's hard to get a portable solution which works in many Python implementations, I need something which works in the most recent CPython 2.7. It doesn't have to be documented.
推荐答案
似乎无法在CPython 2.7中进行早期删除而不进行更改 f
函数的API。
It look like it's not possible to do the early deletion in CPython 2.7 without changing the API of the f
function.
这篇关于如何及早删除函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!