Python _ast 模块,Expr() 实例源码

我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用_ast.Expr()

项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def make_module(code):
        from ..decompiler.disassemble import disassemble
        instructions = Instructions(disassemble(code))
        stmnts = instructions.stmnt()

        doc = pop_doc(stmnts)
        pop_return(stmnts)

#        stmnt = ast.Stmt(stmnts, 0)

        if doc is not None:
            stmnts = [_ast.Expr(value=doc, lineno=doc.lineno, col_offset=0)] + stmnts

        ast_obj = _ast.Module(body=stmnts, lineno=0, col_offset=0)

        return ast_obj
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def MAKE_FUNCTION(self, instr):

        code = self.ast_stack.pop()

        ndefaults = instr.oparg

        defaults = []
        for i in range(ndefaults):
            defaults.insert(0, self.ast_stack.pop())

        function = make_function(code, defaults, lineno=instr.lineno)

        doc = code.co_consts[0] if code.co_consts else None

        if isinstance(doc, str):
            function.body.insert(0, _ast.Expr(value=_ast.Str(s=doc, lineno=instr.lineno, col_offset=0),
                                              lineno=instr.lineno, col_offset=0))


        self.ast_stack.append(function)
项目:konsodi    作者:kharts    | 项目源码 | 文件源码
def get_result(self, code):
        """
        Get result of execution of the line of code
        :param code: string of code
        :type code: str
        :return: str
        """

        try:
            tree = ast.parse(code)
        except Exception, e:
            return str(e)
        if not tree.body:
            return ""
        if isinstance(tree.body[0], Expr):
            try:
                result = eval(code, self.globals)
            except Exception, e:
                return str(e)
            return str(result)
        else:
            try:
                exec code in self.globals
            except Exception, e:
                return str(e)
            return ""
项目:tabkit    作者:yandex-tabkit    | 项目源码 | 文件源码
def parse_assign_expr(ctx, tree, subparser):
    if isinstance(tree, _ast.Assign):
        assert len(tree.targets) == 1 and isinstance(tree.targets[0], _ast.Name)
        return RowExprAssign(tree.targets[0].id, subparser(ctx, tree.value))
    elif isinstance(tree, _ast.Expr):
        if isinstance(tree.value, _ast.Name):
            return RowExprAssign(tree.value.id, subparser(ctx, tree))
        else:
            raise Exception("Please assign expression to a variable")
    else:
        raise Exception("Please assign expression to a variable")
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def isDocstring(self, node):
        """
        Determine if the given node is a docstring, as long as it is at the
        correct place in the node tree.
        """
        return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
                                             isinstance(node.value, ast.Str))
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def getDocstring(self, node):
        if isinstance(node, ast.Expr):
            node = node.value
        if not isinstance(node, ast.Str):
            return (None, None)

        if PYPY:
            doctest_lineno = node.lineno - 1
        else:
            # Computed incorrectly if the docstring has backslash
            doctest_lineno = node.lineno - node.s.count('\n') - 1

        return (node.s, doctest_lineno)
项目:blackmamba    作者:zrzka    | 项目源码 | 文件源码
def isDocstring(self, node):
        """
        Determine if the given node is a docstring, as long as it is at the
        correct place in the node tree.
        """
        return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
                                             isinstance(node.value, ast.Str))
项目:blackmamba    作者:zrzka    | 项目源码 | 文件源码
def getDocstring(self, node):
        if isinstance(node, ast.Expr):
            node = node.value
        if not isinstance(node, ast.Str):
            return (None, None)

        if PYPY:
            doctest_lineno = node.lineno - 1
        else:
            # Computed incorrectly if the docstring has backslash
            doctest_lineno = node.lineno - node.s.count('\n') - 1

        return (node.s, doctest_lineno)
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def MAKE_FUNCTION(self, instr):

        code = self.ast_stack.pop()

        ndefaults = bitrange(instr.oparg, 0, 8)
        nkwonly_defaults = bitrange(instr.oparg, 8, 16)
        nannotations = bitrange(instr.oparg, 16, 32) - 1

        annotations = []
        for i in range(nannotations):
            annotations.insert(0, self.ast_stack.pop())

        kw_defaults = []
        for i in range(nkwonly_defaults * 2):
            kw_defaults.insert(0, self.ast_stack.pop())

        defaults = []
        for i in range(ndefaults):
            defaults.insert(0, self.ast_stack.pop())

        function = make_function(code, defaults, lineno=instr.lineno, annotations=annotations, kw_defaults=kw_defaults)

        doc = code.co_consts[0] if code.co_consts else None

        if isinstance(doc, str):
            function.body.insert(0, _ast.Expr(value=_ast.Str(s=doc, lineno=instr.lineno, col_offset=0),
                                              lineno=instr.lineno, col_offset=0))

        self.ast_stack.append(function)
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def POP_TOP(self, instr):

        node = self.ast_stack.pop()
        node = self.process_ifexpr(node)

        if isinstance(node, _ast.Import):
            return

        if isinstance(node, _ast_Print):
            _ = self.ast_stack.pop()
            self.ast_stack.append(node)
            return

        discard = _ast.Expr(value=node, lineno=instr.lineno, col_offset=0)
        self.ast_stack.append(discard)
项目:overpassify    作者:gappleto97    | 项目源码 | 文件源码
def _(tree, **kwargs):
    options = ''
    if isinstance(tree[0], _ast.Expr) and isinstance(tree[0].value, _ast.Call):
        # test for Settings()
        func = tree[0].value.func.id
        if func == 'Settings':
            keywords = (parse(kwarg) for kwarg in tree[0].value.keywords)
            for key, value in keywords:
                if value[0] == '"':
                    options += '[{}:{}]\n'.format(key, value[1:-1])
                else:
                    options += '[{}:{}]\n'.format(key, value)
            tree = tree[1:]
    return options + '\n'.join(parse(expr) for expr in transform(tree))
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def isDocstring(self, node):
        """
        Determine if the given node is a docstring, as long as it is at the
        correct place in the node tree.
        """
        return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and
                                             isinstance(node.value, ast.Str))
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def getDocstring(self, node):
        if isinstance(node, ast.Expr):
            node = node.value
        if not isinstance(node, ast.Str):
            return (None, None)
        # Computed incorrectly if the docstring has backslash
        doctest_lineno = node.lineno - node.s.count('\n') - 1
        return (node.s, doctest_lineno)
项目:tabkit    作者:yandex-tabkit    | 项目源码 | 文件源码
def awk_filter_map(data_desc, filter_strs, map_strs):
    """
    >>> from tabkit.header import parse_header
    >>> awk, desc = awk_filter_map(
    ...     parse_header('# d p e s c m'),
    ...     ['e==157 and (s>100 or s in [15,30,45])'],
    ...     ['ctr=c/s', 'cpm=ctr*m']
    ... )
    >>> print desc
    DataDesc([DataField('ctr', 'any'), DataField('cpm', 'any')])
    >>> print awk.cmd_line()
    LC_ALL=C awk  -F $'\\t' 'BEGIN{OFS="\\t";}{if((($3 == 157) && (($4 > 100) || (($4 == 15) || ($4 == 30) || ($4 == 45))))){ctr = ($5 / $4);print(ctr,(ctr * $6));}}'
    >>> awk, desc = awk_filter_map(parse_header('# a b'), [], ['__all__'])
    >>> print desc
    DataDesc([DataField('a', 'any'), DataField('b', 'any')])
    """
    ctx = ExprContext(data_desc)

    # parse map
    for map_expr_str in map_strs:
        for node in parse(map_expr_str).body:
            if isinstance(node, _ast.Expr) and isinstance(node.value, _ast.Name) and node.value.id == '__all__':
                for field in data_desc.fields:
                    ctx.set_var(field.name, RowExprAssign(field.name, RowExprField(ctx, field.name)))
            elif isinstance(node, _ast.Expr) and isinstance(node.value, _ast.Name) and node.value.id == '__rest__':
                for field in data_desc.fields:
                    if not ctx.has_var(field.name):
                        ctx.set_var(field.name, RowExprAssign(field.name, RowExprField(ctx, field.name)))
            else:
                expr = parse_rowexpr(ctx, node)
                ctx.set_var(expr.target, expr)

    # parse filter
    nodes = [node for filter_str in filter_strs for node in parse(filter_str).body]
    filter_expr = None
    if len(nodes) == 0:
        pass
    elif len(nodes) == 1:
        filter_expr = parse_expr(ctx, nodes[0])
    else:
        filter_expr = RowExprOp('&&', [parse_expr(ctx, node) for node in nodes])

    awk_cmd, output_desc = awk_filter_map_from_context(ctx, filter_expr, data_desc.order)
    if output_desc:
        output_desc.meta = data_desc.meta
    return awk_cmd, output_desc or data_desc
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def LOAD_BUILD_CLASS(self, instr):

        class_body = []

        body_instr = instr

        while body_instr.opname not in function_ops:
            body_instr = self.ilst.pop(0)
            class_body.append(body_instr)

        call_func = self.decompile_block(class_body, stack_items=[None]).stmnt()

        assert len(call_func) == 1
        call_func = call_func[0]

        func_def = call_func.args[0]
        code = func_def.body
        name = call_func.args[1].s
        bases = call_func.args[2:]

        keywords = call_func.keywords
        kwargs = call_func.kwargs
        starargs = call_func.starargs

        if isinstance(code[0], _ast.Expr):
            _name = code.pop(1)
            _doc = code.pop(1)
        elif isinstance(code[0], _ast.Assign):
            _name = code.pop(0)
        else:
            assert False

        ret = code.pop(-1)

        assert isinstance(ret, _ast.Return)

        class_ = _ast.ClassDef(name=name, bases=bases, body=code, decorator_list=[],
                               kwargs=kwargs, keywords=keywords, starargs=starargs,
                               lineno=instr.lineno, col_offset=0,
                               )

        self.ast_stack.append(class_)