几个月以来,我已经广泛阅读了有关Python中不可变和可变对象的知识,而且我似乎已经开始理解这个概念。我仍然无法发现下面我的代码为什么会产生内存泄漏的问题。字典用作对特定类型的不可变记录的引用。在许多情况下,我会更新现有记录,在这种情况下,仅当两个记录(oldrecord
和newrecord
)不相等时才会更新现有记录。但是,我觉得newrecord
和oldrecord
匹配时newrecord
不会被删除,尽管在这种情况下所有引用似乎都不存在。
我的问题:
下面的代码是基于记录类型选择对字典的引用的良好实践吗?还是应该以其他方式(例如通过dictSwitcher
)来代替?
class myRecordDicts():
def __init__(self, type1Dict=dict(), type2Dict=dict(),
type3Dict=dict(),type4Dict=dict(),type5Dict=dict(),type6Dict=dict(), type7Dict=dict()):
self.type1Dict = type1Dict
self.type2Dict = type2Dict
self.type3Dict = type3Dict
self.type4Dict = type4Dict
self.type5Dict = type5Dict
self.type6Dict = type6Dict
self.type7Dict = type7Dict
def dictSelector(self, record):
dictSwitcher = {
myCustomRecordType1().name: self.type1Dict,
myCustomRecordType2().name: self.type2Dict,
myCustomRecordType3().name: self.type3Dict,
myCustomRecordType4().name: self.type4Dict,
myCustomRecordType5().name: self.type5Dict,
myCustomRecordType6().name: self.type6Dict,
myCustomRecordType7().name: self.type7Dict,
}
return dictSwitcher.get(record.name)
def AddRecordToDict(self, newrecord):
dict = self.dictSelector(newrecord)
recordID = newrecord.id
if recordID in dict:
oldrecord = dict[recordID]
self.MergeExistingRecords(oldrecord,newrecord)
else:
dict[recordID] = newrecord
def MergeExistingRecords(self, oldrecord, newrecord):
# Basic Compare function
oldRecordString = oldrecord.SerializeToString()
newRecordString = newrecord.SerializeToString()
# no need to do anything if same length
if not len(oldRecordString) == len(newRecordString):
oldrecord.CustomMergeFrom(newrecord)
答案 0 :(得分:0)
好吧,似乎总是这样:我在这个问题上工作了几个小时,无法取得进展。在StackExchange上正确提出问题后5分钟,我发现了我的问题:
我需要删除 init 中的引用,因为在实例化myRecordsDicts()
时从未传递过命令,因此以下代码不会泄漏内存:
class myRecordDicts():
def __init__(self):
self.type1Dict = dict()
self.type2Dict = dict()
self.type3Dict = dict()
self.type4Dict = dict()
self.type5Dict = dict()
self.type6Dict = dict()
self.type7Dict = dict()