基本 gTTS 库的使用导致 Python 3.7 中的 RuntimeError
Basic gTTS library usage causes RuntimeError in Python 3.7
我已经在我的机器上成功安装了 gTTS
(Google 文本到语音)库,我 运行 这个简单的代码:
from gtts import gTTS
tts = gTTS('hello')
但是我得到这个错误:
"/usr/local/lib/python3.7/dist-packages/gtts/tts.py", line 114, in __init__
for k, v in locals().items():
RuntimeError: dictionary changed size during iteration.
我做错了什么?
你好像没有做错什么。它似乎是 gTTS
库中的一个简单错误。 The offending code如下:代码仅供调试。
# Debug
for k, v in locals().items():
if k == 'self':
continue
log.debug("%s: %s", k, v)
locals()
returns 局部变量字典。这个字典是局部变量的实时视图,这似乎是一种 undocumented 行为,因此它会在声明新局部变量时动态更新,至少在 Python 的某些版本中(我我正在使用 3.6.2):
>>> the_locals = locals()
>>> len(the_locals)
8
>>> 'x' in the_locals
False
>>> x = 12
>>> len(the_locals)
9
>>> 'x' in the_locals
True
所以,问题是在 __init__
方法中迭代此字典时对 k
的赋值引起的。赋值创建一个新的局部变量,在迭代时将其添加到字典中,这是一个禁忌,会导致引发错误。
解决方案是迭代字典的副本,例如:
for k, v in dict(locals()).items():
...
这似乎是 reported to the library's issue tracker on GitHub in 2018, but the issue was closed without being fixed, presumably because the person who opened the issue did not provide enough information. I suggest opening a new issue 你自己,并提供了尽可能多的信息(对这个 Stack Overflow 问题的 link 可能会有帮助)。
我已经在我的机器上成功安装了 gTTS
(Google 文本到语音)库,我 运行 这个简单的代码:
from gtts import gTTS
tts = gTTS('hello')
但是我得到这个错误:
"/usr/local/lib/python3.7/dist-packages/gtts/tts.py", line 114, in __init__
for k, v in locals().items():
RuntimeError: dictionary changed size during iteration.
我做错了什么?
你好像没有做错什么。它似乎是 gTTS
库中的一个简单错误。 The offending code如下:代码仅供调试。
# Debug
for k, v in locals().items():
if k == 'self':
continue
log.debug("%s: %s", k, v)
locals()
returns 局部变量字典。这个字典是局部变量的实时视图,这似乎是一种 undocumented 行为,因此它会在声明新局部变量时动态更新,至少在 Python 的某些版本中(我我正在使用 3.6.2):
>>> the_locals = locals()
>>> len(the_locals)
8
>>> 'x' in the_locals
False
>>> x = 12
>>> len(the_locals)
9
>>> 'x' in the_locals
True
所以,问题是在 __init__
方法中迭代此字典时对 k
的赋值引起的。赋值创建一个新的局部变量,在迭代时将其添加到字典中,这是一个禁忌,会导致引发错误。
解决方案是迭代字典的副本,例如:
for k, v in dict(locals()).items():
...
这似乎是 reported to the library's issue tracker on GitHub in 2018, but the issue was closed without being fixed, presumably because the person who opened the issue did not provide enough information. I suggest opening a new issue 你自己,并提供了尽可能多的信息(对这个 Stack Overflow 问题的 link 可能会有帮助)。