当我尝试将键、值插入到字典中时,此代码将引发 RuntimeError('字典在迭代期间更改大小')
这是我的代码:
#1. Delcare the Dict val here
dict_plugin_info = {}
#2. For module.__dict__...
for name, attr in module.__dict__.items():
if ((inspect.isclass(attr) and (name.startswith("_") or
attr.__dict__.get("__module__") != module_id))):
continue
if inspect.isclass(attr) and issubclass(attr, PluginInterfaceBase):
inst = attr()
# the follow
plugin_type = inst.plugin_type
keys = list(dict_plugin_info.keys())
if plugin_type not in keys:
###HERE RuntimeError('dictionary changed size during iteration')####
dict_plugin_info[plugin_type] = attr
else:
raise MultiplePluginError("Multiple plugins Type {} Name:{}".format(
plugin_type,
attr.__class__.__name__))
我不知道这是怎么发生的。 我搜索网站最多的答案是当迭代器字典和删除键将引发异常。但我的代码并没有删除密钥。
我不确定
module.__dict__
是否是对变量 dict_plugin_info
的引用。
如果是这样,在
dict_plugin_info[plugin_type] = attr
行中,您正在尝试向 dict_plugin_info
插入新项目,因为您已确认 plugin_type
不在 dict_plugin_info
的键中,这将在迭代过程中更改字典的大小.
d = {1: 1}
for _ in d:
# RuntimeError: dictionary changed size during iteration
d[2] = 2
从上面的代码中我们可以发现,除了要迭代的字典为空之外,不仅删除一个键(本代码中没有显示),而且在迭代过程中插入一个键都会引发这样的异常。
d = dict()
for _ in d:
d[2] = 2 # OK