python 使用此示例来学习如何使用ast修改函数体

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用此示例来学习如何使用ast修改函数体相关的知识,希望对你有一定的参考价值。

# by: Cody Kochmann
# this code works in both python 2 and 3

import ast
import inspect

def insert_line_into_function(fn, line):
    ''' this function essentially lets you safely add source code to the body
        of a function without penalizing its speed with a decorator '''
    # store fn's name for later
    ___fn_name = fn.__name__
    # turn the function into an ast object
    fn_ast = ast.parse(inspect.getsource(fn))
    # insert the line's ast form into the functions ast body
    fn_ast.body[0].body.insert(0, ast.parse(line).body[0])
    # compile the new fn and load it into memory
    exec(compile(fn_ast, '<string>', 'exec'))
    # return the newly loaded function
    return locals()[___fn_name]


# this is the function we are gonna modify with ast
def my_adder(a,b,c):
    d = a+b
    if c%2:
        return a+b
    else:
        return a+d

# heres the code we're gonna inject into my_adder
code_to_inject = 'assert type(a) == int, "a needs to be an int"'

# currently my_adder accepts floats in the first argument
print(my_adder(1,2,3))
print(my_adder(1.0,2,3))

# this my_adder should now throw an assertion for non ints in the first arg
my_adder = insert_line_into_function(my_adder, code_to_inject)

print(my_adder(1,2,3))
print(my_adder(1.0,2,3))  # this line should now raise an AssertionError


以上是关于python 使用此示例来学习如何使用ast修改函数体的主要内容,如果未能解决你的问题,请参考以下文章

python/Pyqt5 - 如何在使用 ast 和获取 ValueError 时避免 eval:attemt 中的格式错误的字符串以提高代码安全性

解析 .py 文件,读取 AST,修改它,然后写回修改后的源代码

Python Ast介绍及应用

如何使用 Python 的 ast 创建类型化的返回? - `def f() -> bool: return True`

如何将 XML 转换为 python AST

我可以从 cppyy 获取 AST