gpt4 book ai didi

Python AST,ast.NodeTransformer,TypeError : required field 'lineno' missing from stmt

转载 作者:太空狗 更新时间:2023-10-30 02:45:38 30 4
gpt4 key购买 nike

如果能学到一些有用的东西,我会非常感激,至于现在,我一直在盲目地行动。所以问题出在python的ast.NodeTransformer上。我想知道是否可以使用这种方式向现有类添加一个函数,而不是生气。

这就是我到目前为止的处理方式。

import ast, inspect, cla # cla is a name of class to which we want to add a new function

klass = inspect.getsource(cla)
tree = ast.parse(klass)
st = '''def function(): return 1'''
Foo = ast.parse(st)

class AddFunc(ast.NodeTransformer):
def visit_ClassDef(self, node):
return node, node.body + Foo.body
self.generic_visit(node)

inst = AddFunc()
stuff = i.visit(tree)

# now the trouble begins, a compiling..
co = compile(stuff, filename='<ast>', mode='exec')

# i get TypeError: required "lineno" missing from stmt

我已经尝试(正如您可能猜到的那样不成功)通过使用来处理这个问题ast 库辅助函数 ast.fix_missing_locations(),和 ast.copy_locaction(),但在大多数情况下,我最终猜测或AddFunc 类中的元组面临 AttributeError。有人知道如何管理吗?

最佳答案

kolko 的回答是正确的,在这种情况下,您需要返回一个 AST 节点。 Foo 在这种情况下是一个模块,它的主体应该是构造函数的语句,可以简单地拼接到类定义中。

有助于理解 ast.NodeTransformer 非常特别:

  • 它通过特定的类名调用visit方法,忽略层次结构
  • 它使用 isinstance(AST)isinstance(list) 计算返回值,忽略其他任何内容!

即使您使用 ast.fix_missing_locations 添加位置数据,您也可能会遇到此错误或密切相关的“lineno missing from expr”。

如果发生这种情况,那是因为你的 AST 有一个不允许出现在那个地方的元素。使用 astunparse.dump 仔细检查结构。在模块体内,只能有语句。在函数 def 中,只能有语句。然后有特定的地方可以有表达式。

要解决这个问题,写出您期望生成的 python,解析它,转储它并根据您生成的内容检查它。

关于Python AST,ast.NodeTransformer,TypeError : required field 'lineno' missing from stmt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23801672/

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