Skip to main content
 首页 » 编程设计

python之如何提前删除函数参数

2024年10月17日11tuyile006

我正在编写一个函数,它接受一个巨大的参数,并运行很长时间。它只需要一半的争论。如果没有更多的引用,函数是否可以删除参数指向的值?

我能够在函数返回后立即将其删除,如下所示:

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__ 最后一个。

请注意,我的代码依赖于 Python 具有引用计数这一事实,一旦对象的引用计数降为零,就会调用 __del__。我希望函数参数的引用计数在函数中间降为零。这可能吗?

请注意,我知道一个解决方法:传递参数列表:

def f(ms): 
  print 'S1' 
  del ms[:] 
  print 'S2' 
class M(object):    
  def __del__(self): 
    print '__del__' 
f([M()]) 

这打印:

S1 
__del__ 
S2 

有没有办法在不更改 API 的情况下提前删除(例如,将列表引入参数)?

如果很难获得适用于许多 Python 实现的可移植解决方案,我需要一些适用于最新的 CPython 2.7 的解决方案。它不必记录在案。

请您参考如下方法:

来自 the documentation :

CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the gc module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (ex: always close files).

除非您自己修改解释器,否则您无法实现您想要的。 __del__ 将在解释器决定执行时调用。