为什么如果要执行的字符串包含列表理解,为什么Python的Exec()函数失败?

发布于 2025-02-12 12:35:17 字数 1142 浏览 0 评论 0原文

我使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凑诗 2025-02-19 12:35:17

根据您给出的东西,这可以正常工作。这里还有其他东西,但我认为问题不是列表理解〜

text = """import re
pattern = re.compile(r"==.+==")
z = [pattern.sub('', x) for x in y]"""

try:
    y = ['hi']
    exec(text)
    assert 'pattern' in locals()
except AssertionError:
    print('Error')

print(z)

输出:

['hi']

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~

text = """import re
pattern = re.compile(r"==.+==")
z = [pattern.sub('', x) for x in y]"""

try:
    y = ['hi']
    exec(text)
    assert 'pattern' in locals()
except AssertionError:
    print('Error')

print(z)

Output:

['hi']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文