compile.py 文件源码

python
阅读 30 收藏 0 点赞 0 评论 0

项目:opyum 作者: Amper 项目源码 文件源码
def ast_to_func(node: ast.AST, old_func: types.FunctionType, file: str = None) -> types.FunctionType:
    """
    Compile node object to function.
    """

    if node and not isinstance(node, (ast.Module, ast.FunctionDef)):
        raise TypeError('Unexpected type for node: {}'.format(str(type(node))))

    if old_func and not isinstance(old_func, types.FunctionType):
        raise TypeError('Unexpected type for old_func: {}'.format(str(type(old_func))))

    result = old_func

    if node and old_func:
        old_code = getattr(old_func, '__code__', None)
        if not isinstance(node, ast.Module):
            mod_node = ast.copy_location(ast.Module(body = [node]), node)
            fun_node = node
        else:
            mod_node = node
            fun_node = node.body[0]
        module = ast_to_code(mod_node, old_code, file=file)
        for code in module.co_consts:
            if not isinstance(code, types.CodeType):
                continue
            if code.co_name == fun_node.name and code.co_firstlineno == fun_node.lineno:
                result.__code__ = code
                break
    else:
        raise ValueError('Not specified value')

    return result
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号