定制Python DSL中的异常追溯

1 投票
1 回答
602 浏览
提问于 2025-04-17 15:26

我正在创建一个基于Python的领域特定语言(DSL),纯粹是为了好玩。目前,它的功能是把文本编译成一个抽象语法树(AST),然后直接执行Python代码。举个例子,如果我写:

a = int(read("input something: "))
b = a**2

它会把这段代码转换成一个像这样的树:

Program:
  VariableSet a:
    Call:
      VariableGet int
      Call:
        VariableGet read
        Literal("input something: ")
  VariableSet b:
    BinaryExpession **:
       VariableGet a
       Literal(2)

树中的每一个节点都会用下面这样的代码来执行:

class VariableSet(object):
    def __init__(self, name, expr):
        self.name = name
        self.expr = expr

    def __call__(self, scope):
        value = self.expr(scope)
        scope.put(self.name, value)
        return value

这个过程运行得非常顺利。我希望的是,当某个指令出现错误时,错误的追踪信息能够指向DSL的源代码,而不是Python的AST代码。目前,我看到的都是:

Traceback (most recent call last):
  File "parser.py", line 164, in <module>
    parse(data)(scope)  
  File "/home/juanplopes/Projects/my-parser/ast.py", line 158, in __call__
    result = expr(scope)
  File "/home/juanplopes/Projects/my-parser/ast.py", line 63, in __call__
    value = self.expr(scope)
  File "/home/juanplopes/Projects/my-parser/ast.py", line 81, in __call__
    return self.method(scope)(*[arg(scope) for arg in self.args])
  File "/home/juanplopes/Projects/my-parser/ast.py", line 81, in __call__
    return self.method(scope)(*[arg(scope) for arg in self.args])
  File "parser.py", line 153, in read
    raise Exception('some exception')
Exception: some exception

有没有办法自定义Python中错误追踪信息的生成方式?

1 个回答

3

是的,但这样做看起来不太好。

你可以去看看在jinja2中是怎么做的

Jinja是一个模板引擎。它处理错误追踪,让错误信息指向模板中的问题。
也许你可以把这个方法应用到你的代码中,让它指向DSL(领域特定语言)中的错误。

撰写回答