Python ast.Expression() Examples

The following are 30 code examples of ast.Expression(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ast , or try the search function .
Example #1
Source File: _assertionnew.py    From python-netsurv with MIT License 6 votes vote down vote up
def generic_visit(self, node):
        # Fallback when we don't have a special implementation.
        if _is_ast_expr(node):
            mod = ast.Expression(node)
            co = self._compile(mod)
            try:
                result = self.frame.eval(co)
            except Exception:
                raise Failure()
            explanation = self.frame.repr(result)
            return explanation, result
        elif _is_ast_stmt(node):
            mod = ast.Module([node])
            co = self._compile(mod, "exec")
            try:
                self.frame.exec_(co)
            except Exception:
                raise Failure()
            return None, None
        else:
            raise AssertionError("can't handle %s" %(node,)) 
Example #2
Source File: test_ast.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_increment_lineno(self):
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src, n=3), src)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        )
        # issue10869: do not increment lineno of root twice
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        ) 
Example #3
Source File: _assertionnew.py    From scylla with Apache License 2.0 6 votes vote down vote up
def generic_visit(self, node):
        # Fallback when we don't have a special implementation.
        if _is_ast_expr(node):
            mod = ast.Expression(node)
            co = self._compile(mod)
            try:
                result = self.frame.eval(co)
            except Exception:
                raise Failure()
            explanation = self.frame.repr(result)
            return explanation, result
        elif _is_ast_stmt(node):
            mod = ast.Module([node])
            co = self._compile(mod, "exec")
            try:
                self.frame.exec_(co)
            except Exception:
                raise Failure()
            return None, None
        else:
            raise AssertionError("can't handle %s" %(node,)) 
Example #4
Source File: test_ast.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_increment_lineno(self):
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src, n=3), src)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        )
        # issue10869: do not increment lineno of root twice
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        ) 
Example #5
Source File: main.py    From couchpotato.provider.t411 with GNU General Public License v2.0 6 votes vote down vote up
def _arithmeticEval(s):
    """
    A safe eval supporting basic arithmetic operations.

    :param s: expression to evaluate
    :return: value
    """
    node = ast.parse(s, mode='eval')

    def _eval(node):
        if isinstance(node, ast.Expression):
            return _eval(node.body)
        elif isinstance(node, ast.Str):
            return node.s
        elif isinstance(node, ast.Num):
            return node.n
        elif isinstance(node, ast.BinOp):
            return _binOps[type(node.op)](_eval(node.left), _eval(node.right))
        else:
            raise Exception('Unsupported type {}'.format(node))

    return _eval(node.body) 
Example #6
Source File: parser.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def __init__(self, source: Union[str, ast.Expression], partial_binding: bool = False):
        """Create new evaluator.

        Args:
            source: Expression of equation to evaluate.
            partial_binding: Allow partial bind of parameters.

        Raises:
            PulseError: When invalid string is specified.
        """
        self._partial_binding = partial_binding
        self._locals_dict = {}
        self._params = set()

        if isinstance(source, ast.Expression):
            self._tree = source
        else:
            try:
                self._tree = ast.parse(source, mode='eval')
            except SyntaxError:
                raise PulseError('%s is invalid expression.' % source)

        # parse parameters
        self.visit(self._tree) 
Example #7
Source File: pyodide.py    From pyodide with Mozilla Public License 2.0 6 votes vote down vote up
def eval_code(code, ns):
    """
    Runs a string of code, the last part of which may be an expression.
    """
    # handle mis-indented input from multi-line strings
    code = dedent(code)

    mod = ast.parse(code)
    if len(mod.body) == 0:
        return None

    if isinstance(mod.body[-1], ast.Expr):
        expr = ast.Expression(mod.body[-1].value)
        del mod.body[-1]
    else:
        expr = None

    if len(mod.body):
        exec(compile(mod, "<exec>", mode="exec"), ns, ns)
    if expr is not None:
        return eval(compile(expr, "<eval>", mode="eval"), ns, ns)
    else:
        return None 
Example #8
Source File: test_ast.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_increment_lineno(self):
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src, n=3), src)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        )
        # issue10869: do not increment lineno of root twice
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        ) 
Example #9
Source File: _assertionnew.py    From python-netsurv with MIT License 6 votes vote down vote up
def generic_visit(self, node):
        # Fallback when we don't have a special implementation.
        if _is_ast_expr(node):
            mod = ast.Expression(node)
            co = self._compile(mod)
            try:
                result = self.frame.eval(co)
            except Exception:
                raise Failure()
            explanation = self.frame.repr(result)
            return explanation, result
        elif _is_ast_stmt(node):
            mod = ast.Module([node])
            co = self._compile(mod, "exec")
            try:
                self.frame.exec_(co)
            except Exception:
                raise Failure()
            return None, None
        else:
            raise AssertionError("can't handle %s" %(node,)) 
Example #10
Source File: asttools.py    From sspam with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def visit_UnaryOp(self, node):
        'Same idea as visit_BinOp'
        if node in self.constexpr:
            # evaluation
            fake_node = ast.Expression(ast.BinOp(node, ast.Mod(),
                                                 ast.Num(self.mod)))
            ast.fix_missing_locations(fake_node)
            code = compile(fake_node, '<constant folding>', 'eval')
            obj_env = globals().copy()
            exec code in obj_env

            value = eval(code, obj_env)
            new_node = ast.Num(value)
            return new_node
        else:
            return self.generic_visit(node) 
Example #11
Source File: asttools.py    From sspam with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def visit_BoolOp(self, node):
        'A custom BoolOp can be used in flattened AST'
        if type(node.op) not in (ast.Add, ast.Mult,
                                 ast.BitXor, ast.BitAnd, ast.BitOr):
            return self.generic_visit(node)
        # get constant parts of node:
        list_cste = [child for child in node.values
                     if isinstance(child, ast.Num)]
        if len(list_cste) < 2:
            return self.generic_visit(node)
        rest_values = [n for n in node.values if n not in list_cste]
        fake_node = Unflattening().visit(ast.BoolOp(node.op, list_cste))
        fake_node = ast.Expression(fake_node)
        ast.fix_missing_locations(fake_node)
        code = compile(fake_node, '<constant folding>', 'eval')
        obj_env = globals().copy()
        exec code in obj_env
        value = eval(code, obj_env)

        new_node = ast.Num(value)
        rest_values.append(new_node)
        return ast.BoolOp(node.op, rest_values) 
Example #12
Source File: asttools.py    From sspam with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def visit_BinOp(self, node):
        'If node is a constant expression, replace it with its evaluated value'
        if node in self.constexpr:
            # evaluation
            fake_node = ast.Expression(ast.BinOp(node, ast.Mod(),
                                                 ast.Num(self.mod)))
            ast.fix_missing_locations(fake_node)
            code = compile(fake_node, '<constant folding>', 'eval')
            obj_env = globals().copy()
            exec code in obj_env
            value = eval(code, obj_env)

            new_node = ast.Num(value)
            return new_node
        else:
            return self.generic_visit(node) 
Example #13
Source File: pattern_matcher.py    From sspam with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, patt_ast, target_ast, rep_ast, nbits=0):
        'Pattern ast should have as root: BinOp, BoolOp, UnaryOp or Call'
        if isinstance(patt_ast, ast.Module):
            self.patt_ast = patt_ast.body[0].value
        elif isinstance(patt_ast, ast.Expression):
            self.patt_ast = patt_ast.body
        else:
            self.patt_ast = patt_ast
        if isinstance(rep_ast, ast.Module):
            self.rep_ast = deepcopy(rep_ast.body[0].value)
        elif isinstance(rep_ast, ast.Expression):
            self.rep_ast = deepcopy(rep_ast.body)
        else:
            self.rep_ast = deepcopy(rep_ast)

        if not nbits:
            getsize = asttools.GetSize()
            getsize.visit(target_ast)
            if getsize.result:
                self.nbits = getsize.result
            # default bitsize is 8
            else:
                self.nbits = 8
        else:
            self.nbits = nbits 
Example #14
Source File: utils.py    From matchpy with MIT License 6 votes vote down vote up
def generic_visit(self, node):
        if self.last_node is not None and hasattr(node, 'col_offset'):
            enode = ast.Expression(self.last_node)
            lambda_code = compile(enode, '<unused>', 'eval')
            lines = self.lines[self.last_node.lineno-1:node.lineno]
            lines[-1] = lines[-1][:node.col_offset]
            lines[0] = lines[0][self.last_node.col_offset:]
            lambda_body_text = ' '.join(l.rstrip(' \t\\').strip() for l in lines)
            while lambda_body_text:
                try:
                    code = compile(lambda_body_text, '<unused>', 'eval')
                    if len(code.co_code) == len(lambda_code.co_code):
                        break
                except SyntaxError:
                    pass
                lambda_body_text = lambda_body_text[:-1]
            self.lambdas.append((lambda_code, lambda_body_text.strip()))
            self.last_node = None
        super().generic_visit(node) 
Example #15
Source File: _assertionnew.py    From py with MIT License 6 votes vote down vote up
def generic_visit(self, node):
        # Fallback when we don't have a special implementation.
        if _is_ast_expr(node):
            mod = ast.Expression(node)
            co = self._compile(mod)
            try:
                result = self.frame.eval(co)
            except Exception:
                raise Failure()
            explanation = self.frame.repr(result)
            return explanation, result
        elif _is_ast_stmt(node):
            mod = ast.Module([node])
            co = self._compile(mod, "exec")
            try:
                self.frame.exec_(co)
            except Exception:
                raise Failure()
            return None, None
        else:
            raise AssertionError("can't handle %s" %(node,)) 
Example #16
Source File: action.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def visit_Call(self, node, return_task=False):
        sub_node = node.func
        while not isinstance(sub_node, ast.Name):
            sub_node = sub_node.value
        py_object = eval(compile(ast.Expression(sub_node), "", "eval"), self._globals)
        if py_object == CalmTask or isinstance(py_object, EntityType):
            task = eval(compile(ast.Expression(node), "", "eval"), self._globals)
            if task is not None and isinstance(task, TaskType):
                if self.target is not None and not task.target_any_local_reference:
                    task.target_any_local_reference = self.target
                if return_task:
                    return task
                self.task_list.append(task)
                self.all_tasks.append(task)
                return
        return self.generic_visit(node) 
Example #17
Source File: step_executor.py    From sos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_value_of_param(name, param_list, extra_dict={}):
    tree = ast.parse(f'__null_func__({param_list})')
    # x.func can be an attribute (e.g. a.b()) and do not have id
    kwargs = [
        x for x in ast.walk(tree)
        if x.__class__.__name__ == 'keyword' and x.arg == name
    ]
    if not kwargs:
        return []
    try:
        return [ast.literal_eval(kwargs[0].value)]
    except Exception:
        return [
            eval(
                compile(
                    ast.Expression(body=kwargs[0].value),
                    filename='<string>',
                    mode="eval"), extra_dict)
        ] 
Example #18
Source File: log_utils.py    From thonny with MIT License 6 votes vote down vote up
def parse_log_line(line):
    split_pos = line.rfind(" at ")
    assert split_pos > 0
    left = line[0:split_pos]
    right = line[split_pos + 4 :].strip()

    tree = ast.parse(left, mode="eval")
    assert isinstance(tree, ast.Expression)
    assert isinstance(tree.body, ast.Call)

    attributes = {
        "event_kind": tree.body.func.id,
        "event_time": strptime(right, "%Y-%m-%dT%H:%M:%S.%f"),
    }

    for kw in tree.body.keywords:
        attributes[kw.arg] = ast.literal_eval(kw.value)

    return attributes 
Example #19
Source File: test_ast.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_increment_lineno(self):
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src, n=3), src)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        )
        # issue10869: do not increment lineno of root twice
        src = ast.parse('1 + 1', mode='eval')
        self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
            'col_offset=0))'
        ) 
Example #20
Source File: action.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def visit_With(self, node):
        parallel_tasks = []
        if len(node.items) > 1:
            raise ValueError(
                "Only a single context is supported in 'with' statements inside the action."
            )
        context = eval(
            compile(ast.Expression(node.items[0].context_expr), "", "eval"),
            self._globals,
        )
        if context.__calm_type__ == "parallel":
            for statement in node.body:
                if not isinstance(statement.value, ast.Call):
                    raise ValueError(
                        "Only calls to 'CalmTask' methods supported inside parallel context."
                    )
                task = self.visit_Call(statement.value, return_task=True)
                if task:
                    parallel_tasks.append(task)
                    self.all_tasks.append(task)
            self.task_list.append(parallel_tasks)
        else:
            raise ValueError(
                "Unsupported context used in 'with' statement inside the action."
            ) 
Example #21
Source File: interpreter.py    From pyqtconsole with MIT License 5 votes vote down vote up
def compile_single_node(node, filename):
    """Compile a 'single' ast.node (expression or statement)."""
    mode = 'eval' if isinstance(node, ast.Expr) else 'exec'
    if mode == 'eval':
        root = ast.Expression(node.value)
    else:
        if sys.version_info >= (3, 8):
            root = ast.Module([node], type_ignores=[])
        else:
            root = ast.Module([node])
    return (compile(root, filename, mode), mode) 
Example #22
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_module(self):
        m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
        self.mod(m, "must have Load context", "single")
        m = ast.Expression(ast.Name("x", ast.Store()))
        self.mod(m, "must have Load context", "eval") 
Example #23
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_example_from_net(self):
        node = ast.Expression(ast.BinOp(ast.Str('xy'), ast.Mult(), ast.Num(3))) 
Example #24
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_copy_location(self):
        src = ast.parse('1 + 1', mode='eval')
        src.body.right = ast.copy_location(ast.Num(2), src.body.right)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), '
            'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, '
            'col_offset=0))'
        ) 
Example #25
Source File: utils.py    From executing with MIT License 5 votes vote down vote up
def check(self, node, value):
        frame = inspect.currentframe().f_back.f_back
        result = eval(
            compile(ast.Expression(node), frame.f_code.co_filename, 'eval'),
            frame.f_globals,
            frame.f_locals,
        )
        assert result == value, (result, value) 
Example #26
Source File: tests.py    From executing with MIT License 5 votes vote down vote up
def check(self, node, value):
        frame = inspect.currentframe().f_back.f_back
        result = eval(
            compile(ast.Expression(node), frame.f_code.co_filename, 'eval'),
            frame.f_globals,
            frame.f_locals,
        )
        assert result == value, (result, value) 
Example #27
Source File: test_dialect.py    From idom with MIT License 5 votes vote down vote up
def eval_html(src, variables=None):
    tree = apply_dialects(src, "html")
    if len(tree.body) > 1 or not isinstance(tree.body[0], ast.Expr):
        raise ValueError(f"Expected a single expression, not {src!r}")
    code = compile(ast.Expression(tree.body[0].value), "<string>", "eval")
    return eval(code, {"html": html}, variables) 
Example #28
Source File: pprinter.py    From quark with Apache License 2.0 5 votes vote down vote up
def leave_AST(self, node):
        self.first = self.stack.pop()[-1]
        if (isinstance(node, (ast.Expression, ast.Declaration)) and
            not isinstance(node, (ast.Fixed, ast.Native))):
            if hasattr(node, "resolved") and node.resolved is not None:
                self.append(",\n$type=%s" % node.resolved)
        if isinstance(node, ast.File) or not self.stack:
            self.append("\n\n")
        self.append(")")
        self.previous = node 
Example #29
Source File: test_ast.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_copy_location(self):
        src = ast.parse('1 + 1', mode='eval')
        src.body.right = ast.copy_location(ast.Num(2), src.body.right)
        self.assertEqual(ast.dump(src, include_attributes=True),
            'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), '
            'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, '
            'col_offset=0))'
        ) 
Example #30
Source File: expressions.py    From terracotta with MIT License 5 votes vote down vote up
def visit_Expression(self, node: ast.Expression) -> Any:
        return self.visit(node.body)