使用ast修改函数源代码的优点

2024-10-01 15:47:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读一个代码配方,它使用一个decorator使用ast模块向函数体添加代码。特别地,添加的代码将一些全局变量降低到局部范围。然后编译ast对象以创建附加到函数的__code__属性的代码对象。装饰器代码如下:

def lower_names(*namelist):
    def lower(func):
        srclines = inspect.getsource(func).splitlines()
        for n, line in enumerate(srclines):
            if '@lower_names' in line:
                break
        src = '\n'.join(srclines[n+1:])
        top = ast.parse(src, mode='exec')

        c1 = NameLower(namelist) # an ast.NodeVisitor subclass that has a
                                 # method to transform the ast node
        c1.visit(top)
        temp = {}
        exec(compile(top, '', 'exec'), temp, temp)
        func.__code__ = temp[func.__name__].__code__
        return func
    return lower

我的问题是为什么要使用ast?为什么不简单地用代码修改函数源代码以降低全局变量并直接编译它(而不是创建ast对象),并将代码对象附加到函数?使用ast有什么好处(比如速度)


Tags: 对象函数代码namestopdefcodeast

热门问题