为什么如果要执行的字符串包含列表理解,为什么Python的Exec()函数失败?
我使用Unittest
模块自动测试学生的代码,并将其写入Jupyter笔记本电脑。
我将笔记本单元读取到nbformat.notebooknode.notebookNode
对象中,将其存储在属性source> source
下的字符串对象中。该字符串在变量单元格
下分配。
然后,我执行代码并执行测试如下所示:
try:
exec(cell.source)
assert 'pattern' in locals()
except AssertionError:
errmsg = 'The variable "pattern" has not been defined.'
在这种情况下,要求学生定义正则表达式,(2)在命名的字符串列表中用空字符串替换匹配项,nation nater of Code> y
。
以下示例使用列表理解来实现此消息:
import re
pattern = re.compile(r"==.+==")
z = [pattern.sub('', x) for x in y]
此代码在jupyter笔记本中没有错误运行,但是测试失败了以下错误:
exec(self.cell.source)
File "<string>", line 4, in <module>
File "<string>", line 4, in <listcomp>
NameError: name 'pattern' is not defined
如果我正确理解的话,列表理解无法找到名称pattern
在上线上定义。
但是,如果列表理解被for循环替换,则测试通过,如下所示:
import re
pattern = re.compile(r"==.+==")
z = []
for x in y:
z.append(pattern.sub(repl='', string=x))
为什么使用列表理解会导致测试失败?
I use the unittest
module to automatically test my students' code, which they write into Jupyter Notebooks.
I read the Notebook cells into nbformat.notebooknode.NotebookNode
objects, which store the code contained in the cell as a string object under the attribute source
. This string is assigned under the variable cell
.
I then execute the code and perform tests as exemplified below:
try:
exec(cell.source)
assert 'pattern' in locals()
except AssertionError:
errmsg = 'The variable "pattern" has not been defined.'
In this case, the students are asked to (1) define a regular expression and (2) to replace matches with empty strings in a pre-existing list of strings named y
.
The following example achieves this using a list comprehension:
import re
pattern = re.compile(r"==.+==")
z = [pattern.sub('', x) for x in y]
This code runs without errors in the Jupyter Notebook, but the tests fail with the following error:
exec(self.cell.source)
File "<string>", line 4, in <module>
File "<string>", line 4, in <listcomp>
NameError: name 'pattern' is not defined
If I've understood correctly, the list comprehension cannot find the name pattern
defined on the previous line.
However, the test passes if the list comprehension is replaced with a for loop, as exemplified below:
import re
pattern = re.compile(r"==.+==")
z = []
for x in y:
z.append(pattern.sub(repl='', string=x))
Why does the use of a list comprehension cause the test to fail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您给出的东西,这可以正常工作。这里还有其他东西,但我认为问题不是列表理解〜
输出:
Based off of what you've given, this works fine. There's something else missing here, but I don't think the issue is the list comprehension~
Output: