gpt4 book ai didi

python - 如果存在嵌套类定义,为什么 python 编译不起作用?

转载 作者:行者123 更新时间:2023-12-01 05:05:09 25 4
gpt4 key购买 nike

我尝试编译有效的 python 代码,但没有成功 - 程序在 python 中工作,但无法编译为 ast。我不知道为什么会发生这种情况 - 我检查了 space\tabs 但我认为这不是重要的。

class NdbModelForm(unittest.TestCase):
def testLoadPostStringProperty(self):
class DeleteMe(ndb.Model):
name = ndb.StringProperty()
pass

代码不太复杂,但是当我想解析此代码时,我得到了这样的无效异常:

    codeTree = ast.parse(inspect.getsource(mroObject))
File "C:\root\Python27\lib\ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
class DeleteMe(ndb.Model):
^
IndentationError: unexpected indent

如何修复此代码或解决方法问题?

最佳答案

看起来答案很简单:

codeTree = ast.parse(inspect.getsource(mroObject))

应替换为:

codeTree = ast.parse(textwrap.dedent(inspect.getsource(mroObject)))

看起来很简单,但很难找到这样的解释。

关于python - 如果存在嵌套类定义,为什么 python 编译不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25193645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com