问题描述
我试图引用一个列表(reclist)并将其附加到另一个列表(数据),但是当我尝试取消引用它时,出现以下错误。此方法是否错误?或者我该如何解决此错误?
import gc
def deref(id_):
return next(ob for ob in gc.get_objects() if id(ob) == id_)
reclist = []
data = []
for j in range(10):
reclist = ["ID","A","C",3535325]
ref = id(reclist)
data.append(ref) # loading reference
for rec in data:
output = deref(rec)
print(output)
错误消息:
Traceback (most recent call last):
File "ref_deref.py",line 14,in <module>
output = deref(rec)
File "ref_deref.py",line 3,in deref
return next(ob for ob in gc.get_objects() if id(ob) == id_)
stopiteration
解决方法
错误消息是因为您没有包装deref
来处理StopIteration
异常:
def deref(id_):
try:
return next(ob for ob in gc.get_objects() if id(ob) == id_)
except StopIteration:
pass
输出:
None
['ID','A','C',3535325]
[]
['ID',3535325]